# Select specific columnsselected_columns = df.select("id", "name", "price")print("Selected Columns:")selected_columns.show(10)
Filter
施加条件筛选行
#Filter rows based on a conditionfiltered_data = df.filter(df.quantity>20)print("Filtered Data: ",filtered_data.count())filtered_data.show()
GroupBy and Aggregations
聚合
# GroupBy and Aggregationsgrouped_data = df.groupBy("category").agg({"quantity": "sum", "price": "avg"})print("Grouped and Aggregated Data:")grouped_data.show()
toDF
根据已有的Dataframe创建新的Dataframe
此处取name和price两列改名为pname和price of product再显示前五行
df.select('name','price').toDF('pname','price of product').show(5)
Join
按照指定的列把多个DataFrame组合起来
# Join with another DataFramedf2 = df.select("id", "category").limit(10)joined_data = df.join(df2, "id", "inner")print("Joined Data:")joined_data.show()
Sort
顺序排列orderBy()
# sort by a columnsorted_data = df.orderBy("price")print("Sorted Data:")sorted_data.show(10)
倒序排列同样使用orderBy()
使用desc()表示倒序(需要从pyspark.sql.functions中import)
但倒序有两种不同的表示
orderBy(desc("col1"))
orderBy(col("col2").desc())
# sort by a column descfrom pyspark.sql.functions import col,descsorted_data = df.orderBy(col("price").desc(),col("id").desc())print("Sorted Data Descending:")sorted_data.show(10)
Distinct
取出不重复的行, 使用distinct()
# get distinct product categorydistinct_rows = df.select("category").distinct()print("Distinct Product Categoryies")distinct_rows.show()
Drop
移除指定的列, drop()
由于dataframe是不可变的,因此此处的drop只是屏蔽列的显示,并不是删除
# drop columndropped_column = df.drop("category")print("dropped column")dropped_column.show(10)
WithColumn
添加新计算出来的列,常用于表示平均值/总和
# add a new calculated columndf_with_new_column = df.withColumn("sum",df.quantity*df.price)print("Data frame with new column")df_with_new_column.show(10)
Alias
将列改名,常用withColumnRenamed
#rename columns using aliasdf_with_alias = df.withColumnRenamed("old name","new name")print("DataFrame with Aliased Column:")df_with_alias.show(10)
# retrieve the 'name' and 'quantity' columns from dfdf_rdds_map = df_rdds.map(lambda x:(x['name'],x['quantity']))print('map:\n',df_rdd_map.take(5),'\n')#multiply each value in 'quantity' by 10df_rdds_mapvalues = df_rdds_map.mapValues(lambda x: [x,x*10])print('mapvalues:\n',df_rdd_mapvalue.take(5),'\n')