PySpark DataFrame 入門

PySpark 入門

Benjamin Schmidt

Data Engineer

關於 DataFrame

  • DataFrame:表格格式(列/欄)
  • 支援類 SQL 操作
  • 類似 pandas DataFrame 或 SQL TABLE
  • 結構化資料

Dataframes

PySpark 入門

從檔案儲存建立 DataFrame

# Create a DataFrame from CSV
census_df = spark.read.csv('path/to/census.csv', header=True, inferSchema=True)
PySpark 入門

列印 DataFrame

# Show the first 5 rows of the DataFrame
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 結構(Schema)

# Show the schema
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() will return the total row numbers in the DataFrame
row_count = census_df.count()
print(f'Number of rows: {row_count}')
# groupby() allows the use of sql-like aggregations
census_df.groupBy('gender').agg({'salary_usd': 'avg'}).show()

Other aggregate functions are:

  • sum()
  • min()
  • max()
PySpark 入門

PySpark 分析常用函式

  • .select():選取特定欄位
  • .filter():依條件篩選列
  • .groupBy():依一個或多個欄位分組
  • .agg():對分組資料做彙總
PySpark 入門

關鍵函式範例

# Using filter and select, we can narrow down our 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 入門

一起來練習吧!

PySpark 入門

Preparing Video For Download...