PySpark DataFrame 소개

PySpark 입문

Benjamin Schmidt

Data Engineer

DataFrame 소개

  • DataFrame: 표 형식(행/열)
  • SQL 유사 연산 지원
  • Pandas DataFrame 또는 SQL TABLE과 유사
  • 구조적 데이터

Dataframes

PySpark 입문

파일 스토어에서 DataFrame 생성

# CSV에서 DataFrame 생성
census_df = spark.read.csv('path/to/census.csv', header=True, inferSchema=True)
PySpark 입문

DataFrame 출력

# DataFrame의 처음 5개 행 표시
census_df.show()


   age  education.num marital.status         occupation income
0   90              9        Widowed                  ?  <=50K
1   82              9        Widowed    Exec-managerial  <=50K
2   66             10        Widowed                  ?  <=50K
3   54              4       Divorced  Machine-op-inspct  <=50K
4   41             10      Separated     Prof-specialty  <=50K
PySpark 입문

DataFrame 스키마 출력

# 스키마 표시
census_df.printSchema()

Output: root |-- age: integer (nullable = true) |-- education.num: integer (nullable = true) |-- marital.status: string (nullable = true) |-- occupation: string (nullable = true) |-- income: string (nullable = true)
PySpark 입문

PySpark DataFrame 기본 분석

# .count()는 DataFrame의 총 행 수를 반환합니다
row_count = census_df.count()
print(f'Number of rows: {row_count}')
# groupby()로 SQL 유사 집계를 수행할 수 있습니다
census_df.groupBy('gender').agg({'salary_usd': 'avg'}).show()

다른 집계 함수:

  • sum()
  • min()
  • max()
PySpark 입문

PySpark 분석 핵심 함수

  • .select(): 특정 열 선택
  • .filter(): 조건으로 행 필터링
  • .groupBy(): 한 개 이상 열로 그룹화
  • .agg(): 그룹에 집계 함수 적용
PySpark 입문

핵심 함수 예시

# filter와 select로 DataFrame을 좁힐 수 있습니다
filtered_census_df = census_df.filter(df['age'] > 50).select('age', 'occupation')
filtered_census_df.show()

Output +---+------------------+ |age| occupation | +---+------------------+ | 90| ?| | 82| Exec-managerial| | 66| ?| | 54| Machine-op-inspct| +---+------------------+
PySpark 입문

Ayo berlatih!

PySpark 입문

Preparing Video For Download...