PySpark 入門
Ben Schmidt
Data Engineer
.na.drop()でnull値の行を削除する# Drop rows with any nulls df_cleaned = df.na.drop()# Filter out nulls df_cleaned = df.where(col("columnName").isNotNull())
.na.fill({"column": value) を使用して、null を特定の値 {{2}} に置き換えます# Fill nulls in the age column with the value 0
df_filled = df.na.fill({"age": 0})
.withColumn() を使用して、計算結果または既存の列に基づいて新しい列を追加します# Create a new column 'age_plus_5'
df = df.withColumn("age_plus_5", df["age"] + 5)
withColumnRenamed()を使用してください# Rename the 'age' column to 'years'
df = df.withColumnRenamed("age", "years")
drop()不要な列を削除します# Drop the 'department' column
df = df.drop("department")
.filter()を使用して、特定の条件に基づいて行を選択します# Filter rows where salary is greater than 50000
filtered_df = df.filter(df["salary"] > 50000)
.groupBy() と集約関数(例: .sum()、.avg())を使ってデータ {{2}} を要約する# Group by department and calculate the average salary
grouped_df = df.groupBy("department").avg("salary")
フィルタリング
+------+---+-----------------+
|salary|age| occupation |
+------+---+-----------------+
| 60000| 45|Exec-managerial |
| 70000| 35|Prof-specialty |
+------+---+-----------------+
GroupBy
`
+----------+-----------+
|department|avg(salary)|
+----------+-----------+
| HR| 80000.0|
| IT| 70000.0|
+----------+-----------+
`
# Drop rows with any nulls df_cleaned = df.na.drop()#Drop nulls on a column df_cleaned = df.where(col("columnName").isNotNull())# Fill nulls in the age column with the value 0 df_filled = df.na.fill({"age": 0})
.withColumn()を使用して、計算や既存の列に基づく新しい列を追加する。 構文: .withColumn("new_col_name", "original transformation")
# Create a new column 'age_plus_5'
df = df.withColumn("age_plus_5", df["age"] + 5)
withColumnRenamed() を使用して列名を変更する
構文: withColumnRenamed(旧列名,新しい列名`
# Rename the 'age' column to 'years'
df = df.withColumnRenamed("age", "years")
drop() to remove unnecessary columns
Syntax: .drop(列名)# Drop the 'department' column
df = df.drop("department")
# Filter rows where salary is greater than 50000
filtered_df = df.filter(df["salary"] > 50000)
.groupBy() and aggregate functions (e.g., .sum(), .avg()) to summarize data # Group by department and calculate the average salary
grouped_df = df.groupBy("department").avg("salary")
PySpark 入門