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 ด้วยค่าที่กำหนด# 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() และฟังก์ชัน aggregate (เช่น .sum(), .avg()) เพื่อสรุปข้อมูล# Group by department and calculate the average salary
grouped_df = df.groupBy("department").avg("salary")
Filtering
+------+---+-----------------+
|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() เพื่อเพิ่มคอลัมน์ใหม่จากการคำนวณหรือคอลัมน์ที่มีอยู่ Syntax: .withColumn("new_col_name", "original transformation")
# Create a new column 'age_plus_5'
df = df.withColumn("age_plus_5", df["age"] + 5)
ใช้ withColumnRenamed() เพื่อเปลี่ยนชื่อคอลัมน์
Syntax: withColumnRenamed(old column name,new column name`
# Rename the 'age' column to 'years'
df = df.withColumnRenamed("age", "years")
drop() เพื่อลบคอลัมน์ที่ไม่ต้องการ
Syntax: .drop(column name)# Drop the 'department' column
df = df.drop("department")
# Filter rows where salary is greater than 50000
filtered_df = df.filter(df["salary"] > 50000)
.groupBy() และฟังก์ชัน aggregate (เช่น .sum(), .avg()) เพื่อสรุปข้อมูล # Group by department and calculate the average salary
grouped_df = df.groupBy("department").avg("salary")
PySpark เบื้องต้น