Python 根据列值对pyspark数据帧进行排序

Python 根据列值对pyspark数据帧进行排序,python,dataframe,pyspark,pyspark-sql,Python,Dataframe,Pyspark,Pyspark Sql,我是Spark的初学者,我正在为我的问题寻找解决方案。 我试图根据每列包含的null值的数量以升序对数据帧进行排序 例如: 数据: 排序后,数据帧应为: Column3 Colum2 Column1 我所能做的就是计算每列的空值 data.select([count(when(col(c).isNull(), c)).alias(c) for c in data.columns]) 现在,我不知道如何继续。我希望您能帮助我。我的解决方案,它可以按照您的要求工作: #Based

我是Spark的初学者,我正在为我的问题寻找解决方案。 我试图根据每列包含的null值的数量以升序对数据帧进行排序

例如: 数据:

排序后,数据帧应为:

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()

这回答了你的问题吗?相关:非常感谢您的回复。但是,它在字典行“不支持的类文件主版本55”中显示了一个错误。我会试着把它修好。多谢各位much@Mus您正在使用Python2.x吗?因为我的实现是针对Python3.xf或Python2.x的,所以请看这篇文章:如果我的答案对您合适,您可以接受,如果您愿意:-)是的,我正在使用Python2.7。我试过python3,你的答案100%有效。再次感谢
#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()