# 사용자데이터 확인
display(dbutils.fs.ls('/FileStore/tables/'))
■ 데이터프레임으로 가져오기
ㅁ spark.read.csv 활용
# 사용자 데이터--> DataFrame으로 읽기
# 한글깨짐 현상 방지를 위해 encoding 설정해서 불러오기
df_usertbl = spark.read.csv("/FileStore/tables/TextDown_pm031323_1000.csv", header = True, encoding = 'euc-kr')
display(df_usertbl)
■ 데이터 타입 보기
# 데이터 타입 보기
df_usertbl.printSchema()
■ 데이터프레임 생성하기
ㅁ spark.read.options 활용
path = '/FileStore/tables/TextDown_pm031323_1000.csv'
df_export = spark.read.options(header=True, inferSchema=True, encoding = 'euc-kr').csv(path)
# 객체 타입 확인
print(type(df_export))
# 데이터 프린트 개수 제한 15
display(df_export.limit(15))
ㅁ Visualization 활용
■ 데이터프레임을 Python Pandas로 전환하기
# 객체 타입 확인
print(type(pdf_export))
# Pyspark DF -> Python Pandas 프레임으로 변환
pdf_export = df_export.toPandas()
# 객체 타입 확인
print(type(pdf_export))
# 판다스 데이터프레임 형식으로 간단한 시각화 지원 안됨
pdf_export.head(10)
# 제공 데이터셋 'diamonds' 불러오기
df_diamonds = spark.read.csv("/databricks-datasets/Rdatasets/data-001/csv/ggplot2/diamonds.csv", header=True)
# 타입 확인
print(type(df_diamonds))
# 데이터 프린트
display(diamonds)
■ Dataframe에서 계산하기
# 모듈 호출
import pandas as pd
from pyspark.sql.functions import avg
# diamonds 데이터 색상(color)별로 가격(price) 평균 구하기
display(diamonds.select("color","price").groupBy("color").agg(avg("price")).sort("color"))
FileStore는 DBFS(Databricks File System)의 특수 폴더로 파일을 저장하고 웹 브라우저에서 파일에 액세스할 수 있음
이미지 및 라이브러리와 같은 파일을 저장
다운로드하려는 출력 파일을 로컬 데스크탑에 저장
로컬 데이크톱에서 CSV 및 기타 데이터 파일을 업로드하여 Databricks에서 처리
■ 파일 저장 위치
/FileStore/jars 업로드하는 하이브러리 저장. 삭제시 라이브러리 작동 안함.
/FileStore/tables UI를 사용하여 가져오는 파일 저장. 삭제시 이 파일에서 만든 테이블 액세스 불가.
■ FileStore에 파일 저장
dbutils.fs.put을 사용하여 임의이 텍스트 파일을 저장할 수 있음
# 파일 저장
dbutils.fs.put("/FileStore/my-stuff/my-file.txt", "This is the actual text that will be saved to disk. Like a 'Hello world!' example")
# 저장된 파일 확인
display(dbutils.fs.ls('/'))