PySpark로 배우는 빅데이터 기초
Upendra Devisetty
Science Analyst, CyVerse
DataFrame 연산: 변환(Transformations)과 동작(Actions)
DataFrame 변환:
DataFrame 동작:
정정: printSchema()는 모든 Spark 데이터셋/데이터프레임의 메서드이며 액션이 아닙니다
select() 변환은 DataFrame에서 열을 부분 선택합니다df_id_age = test.select('Age')
show() 동작은 DataFrame의 처음 20개 행을 출력합니다df_id_age.show(3)
+---+
|Age|
+---+
| 17|
| 17|
| 17|
+---+
only showing top 3 rows
filter() 변환은 조건에 따라 행을 필터링합니다new_df_age21 = new_df.filter(new_df.Age > 21)
new_df_age21.show(3)
+-------+------+---+
|User_ID|Gender|Age|
+-------+------+---+
|1000002| M| 55|
|1000003| M| 26|
|1000004| M| 46|
+-------+------+---+
only showing top 3 rows
groupby()는 변수를 기준으로 그룹화합니다test_df_age_group = test_df.groupby('Age')
test_df_age_group.count().show(3)
+---+------+
|Age| count|
+---+------+
| 26|219587|
| 17| 4|
| 55| 21504|
+---+------+
only showing top 3 rows
orderby()는 하나 이상의 열을 기준으로 DataFrame을 정렬합니다test_df_age_group.count().orderBy('Age').show(3)
+---+-----+
|Age|count|
+---+-----+
| 0|15098|
| 17| 4|
| 18|99660|
+---+-----+
only showing top 3 rows
dropDuplicates()는 DataFrame의 중복 행을 제거합니다test_df_no_dup = test_df.select('User_ID','Gender', 'Age').dropDuplicates()
test_df_no_dup.count()
5892
withColumnRenamed()는 DataFrame의 열 이름을 변경합니다test_df_sex = test_df.withColumnRenamed('Gender', 'Sex')
test_df_sex.show(3)
+-------+---+---+
|User_ID|Sex|Age|
+-------+---+---+
|1000001| F| 17|
|1000001| F| 17|
|1000001| F| 17|
+-------+---+---+
printSchema()는 DataFrame의 열 타입을 출력합니다test_df.printSchema()
|-- User_ID: integer (nullable = true)
|-- Product_ID: string (nullable = true)
|-- Gender: string (nullable = true)
|-- Age: string (nullable = true)
|-- Occupation: integer (nullable = true)
|-- Purchase: integer (nullable = true)
columns 연산자는 DataFrame의 열 이름을 반환합니다test_df.columns
['User_ID', 'Gender', 'Age']
describe()는 DataFrame의 수치 열에 대한 요약 통계를 계산합니다test_df.describe().show()
+-------+------------------+------+------------------+
|summary| User_ID|Gender| Age|
+-------+------------------+------+------------------+
| count| 550068|550068| 550068|
| mean|1003028.8424013031| null|30.382052764385495|
| stddev|1727.5915855307312| null|11.866105189533554|
| min| 1000001| F| 0|
| max| 1006040| M| 55|
+-------+------------------+------+------------------+
PySpark로 배우는 빅데이터 기초