根据列值对pyspark数据框进行排序
Sorting pyspark dataframe accroding to columns values
我是 Spark 的初学者,我正在为我的问题寻找解决方案。
我正在尝试根据每列包含的 空值 的数量按升序对数据框进行排序。
例如:
数据:
column1 Column2 Column3
a d h
b null null
null e i
null f h
null null k
c g l
排序后,dataframe 应该是:
Column3 Colum2 Column1
我所能做的就是计算每一列的空值。
data.select([count(when(col(c).isNull(), c)).alias(c) for c in data.columns])
现在,我不知道如何继续。我希望你能帮助我。
我的解决方案,如你所愿:
#Based on your code
df=df.select([count(when(col(c).isNull(), c)).alias(c) for c in df.columns])
# Convert dataframe to dictionary (Python 3.x)
dict = list(map(lambda row: row.asDict(), df.collect()))[0]
# Create a dictionary with sorted values based on keys
sorted_dict={k: v for k, v in sorted(dict.items(), key=lambda item: item[1])}
# Create a sorted list with the column names
sorted_cols = [c for c in sorted_dict.keys()]
# With .select() method we re-order the dataframe
df.select(sorted_cols).show()
我是 Spark 的初学者,我正在为我的问题寻找解决方案。 我正在尝试根据每列包含的 空值 的数量按升序对数据框进行排序。
例如: 数据:
column1 Column2 Column3
a d h
b null null
null e i
null f h
null null k
c g l
排序后,dataframe 应该是:
Column3 Colum2 Column1
我所能做的就是计算每一列的空值。
data.select([count(when(col(c).isNull(), c)).alias(c) for c in data.columns])
现在,我不知道如何继续。我希望你能帮助我。
我的解决方案,如你所愿:
#Based on your code
df=df.select([count(when(col(c).isNull(), c)).alias(c) for c in df.columns])
# Convert dataframe to dictionary (Python 3.x)
dict = list(map(lambda row: row.asDict(), df.collect()))[0]
# Create a dictionary with sorted values based on keys
sorted_dict={k: v for k, v in sorted(dict.items(), key=lambda item: item[1])}
# Create a sorted list with the column names
sorted_cols = [c for c in sorted_dict.keys()]
# With .select() method we re-order the dataframe
df.select(sorted_cols).show()