与 PySpark DataFrame 交互

使用 PySpark 的大数据基础

Upendra Devisetty

Science Analyst, CyVerse

PySpark 中的 DataFrame 操作符

  • DataFrame 操作:转换与动作

  • DataFrame 转换:

    • select(), filter(), groupby(), orderby(), dropDuplicates(), withColumnRenamed()
  • DataFrame 动作:

    • printSchema(), head(), show(), count(), columns, describe()

    更正:printSchema() 适用于任意 Spark 数据集/DataFrame,不是动作

使用 PySpark 的大数据基础

select() 与 show()

  • 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
使用 PySpark 的大数据基础

filter() 与 show()

  • 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
使用 PySpark 的大数据基础

groupby() 与 count()

  • 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
使用 PySpark 的大数据基础

orderby() 转换

  • orderby() 按一列或多列排序 DataFrame
test_df_age_group.count().orderBy('Age').show(3)
+---+-----+
|Age|count|
+---+-----+
|  0|15098|
| 17|    4|
| 18|99660|
+---+-----+
only showing top 3 rows
使用 PySpark 的大数据基础

dropDuplicates()

  • dropDuplicates() 删除 DataFrame 中的重复行
test_df_no_dup = test_df.select('User_ID','Gender', 'Age').dropDuplicates()
test_df_no_dup.count()
5892
使用 PySpark 的大数据基础

withColumnRenamed 转换

  • 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|
+-------+---+---+
使用 PySpark 的大数据基础

printSchema()

  • 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)
使用 PySpark 的大数据基础

columns 动作

  • columns 返回 DataFrame 的列名
test_df.columns
['User_ID', 'Gender', 'Age']
使用 PySpark 的大数据基础

describe() 动作

  • 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 的大数据基础

Vamos praticar!

使用 PySpark 的大数据基础

Preparing Video For Download...