我有一个包含数字的两列数据框,我需要按行排序,而不是按行排序。在任何地方都给出了如何按列对数据帧进行排序,但我无法找到如何在pyspark中对数据帧的所有行进行排序
col1 col2
2 1
3 2
预期输出
col1 col2
1 2
2 3
答案 0 :(得分:0)
您可能需要一些解决方法来产生您想要的结果。
以下是基于行对数据进行排序的示例。
从您的数据框架中,您可能需要先创建索引。
df = spark.createDataFrame([['index1',3,2,1], ['index2',2,1,3]], ['index', 'a', 'b', 'c'])
columns = [i for i in df.columns if i != 'index']
df.show()
def sort_row_df(row_to_sort):
row_data = df.filter(col('index')==row_to_sort).collect()[0]
sorted_row = sorted([[row_data[col_], col_] for col_ in columns])
rearrange_col = [i[1] for i in sorted_row]
return df.select("index", *rearrange_col)
假设您希望根据行' index1',
进行排序row_to_sort = 'index1'
sorted_df = sort_row_df(row_to_sort)
sorted_df.show()
根据行' index2',
进行排序row_to_sort = 'index2'
sorted_df = sort_row_df(row_to_sort)
sorted_df.show()
如果你想根据行对所有数据进行排序,我建议你只需转置所有数据,对其进行排序,然后再将其转置回来。您可以参考how to transpose df in pyspark.