PySpark 入门
Benjamin Schmidt
Data Engineer

# 从 CSV 创建 DataFrame
census_df = spark.read.csv('path/to/census.csv', header=True, inferSchema=True)
# 显示前 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
# 显示 schema census_df.printSchema()输出: root |-- age: integer (nullable = true) |-- education.num: integer (nullable = true) |-- marital.status: string (nullable = true) |-- occupation: string (nullable = true) |-- income: string (nullable = true)
# .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().select():选择特定列.filter():按条件筛选行.groupBy():按一列或多列分组.agg():对分组数据做聚合# 用 filter 和 select 缩小 DataFrame 范围 filtered_census_df = census_df.filter(df['age'] > 50).select('age', 'occupation') filtered_census_df.show()输出 +---+------------------+ |age| occupation | +---+------------------+ | 90| ?| | 82| Exec-managerial| | 66| ?| | 54| Machine-op-inspct| +---+------------------+
PySpark 入门