Thao tác cột DataFrame

Làm sạch dữ liệu với PySpark

Mike Metzger

Data Engineering Consultant

Ôn tập DataFrame

DataFrame:

  • Gồm hàng & cột
  • Bất biến
  • Dùng các phép biến đổi để chỉnh dữ liệu
# Trả về các hàng có name bắt đầu bằng "M"
voter_df.filter(voter_df.name.like('M%'))

# Chỉ trả về name và position voters = voter_df.select('name', 'position')
Làm sạch dữ liệu với PySpark

Các biến đổi DataFrame thường dùng

  • Filter / Where
    voter_df.filter(voter_df.date > '1/1/2019') # hoặc voter_df.where(...)
    
  • Select
    voter_df.select(voter_df.name)
    
  • withColumn
    voter_df.withColumn('year', voter_df.date.year)
    
  • drop
    voter_df.drop('unused_column')
    
Làm sạch dữ liệu với PySpark

Lọc dữ liệu

  • Loại null
  • Loại giá trị bất thường
  • Tách dữ liệu từ nguồn gộp
  • Phủ định với ~
    voter_df.filter(voter_df['name'].isNotNull())
    voter_df.filter(voter_df.date.year > 1800)
    voter_df.where(voter_df['_c0'].contains('VOTE'))
    voter_df.where(~ voter_df._c1.isNull())
    
Làm sạch dữ liệu với PySpark

Biến đổi chuỗi theo cột

  • Nằm trong pyspark.sql.functions
    import pyspark.sql.functions as F
    
  • Áp dụng theo cột như biến đổi
    voter_df.withColumn('upper', F.upper('name'))
    
  • Có thể tạo cột trung gian
    voter_df.withColumn('splits', F.split('name', ' '))
    
  • Có thể ép kiểu khác
    voter_df.withColumn('year', voter_df['_c4'].cast(IntegerType()))
    
Làm sạch dữ liệu với PySpark

Hàm cho cột ArrayType()

Các hàm/biến đổi tiện ích để làm việc với ArrayType()

.size(<column>) - trả về độ dài cột ArrayType()

.getItem(<index>) - lấy phần tử tại chỉ số của cột danh sách.

Làm sạch dữ liệu với PySpark

Hãy thực hành!

Làm sạch dữ liệu với PySpark

Preparing Video For Download...