Lọc DataFrame của bạn
Trong bài trước, bạn đã trích chọn dữ liệu bằng toán tử select() — chủ yếu dùng để trích chọn theo cột của DataFrame. Vậy nếu bạn muốn trích chọn DataFrame dựa trên một điều kiện thì sao (ví dụ: chọn tất cả các hàng có giới tính là Female). Trong bài này, bạn sẽ lọc các hàng trong DataFrame people_df mà 'sex' là female và male để tạo hai tập dữ liệu khác nhau. Cuối cùng, bạn sẽ đếm số hàng trong từng tập dữ liệu đó.
Lưu ý, bạn đã có sẵn SparkSession spark và DataFrame people_df trong không gian làm việc của mình.
Bài tập này là một phần của khóa học
Nền tảng Big Data với PySpark
Hướng dẫn bài tập
- Lọc DataFrame
people_dfđể chọn tất cả các hàng có giới tính female vào DataFramepeople_df_female. - Lọc DataFrame
people_dfđể chọn tất cả các hàng có giới tính male vào DataFramepeople_df_male. - Đếm số hàng trong các DataFrame
people_df_femalevàpeople_df_male.
Bài tập tương tác thực hành trực tiếp
Hãy thử làm bài tập này bằng cách hoàn thành đoạn mã mẫu này.
# Filter people_df to select females
people_df_female = people_df.____(people_df.____ == "female")
# Filter people_df to select males
people_df_male = people_df.____(____ == "____")
# Count the number of rows
print("There are {} rows in the people_df_female DataFrame and {} rows in the people_df_male DataFrame".format(people_df_female.____(), people_df_male.____()))