我可以看到用于垂直排序记录的解决方案,但是我想水平排列数据框中的数据子集。
这是我要排序的数据的数据框:
account_num Word_0 Word_1 Word_2 Word_3 Word_4
123 Silver Platinum Osmium
456 Platinum
789 Silver Rhodium Platinum Osmium
这是我想要的输出:
account_num Word_0 Word_1 Word_2 Word_3 Word_4
123 Platinum Osmium Silver
456 Platinum
789 Rhodium Platinum Osmium Silver
根据此数据框内的顺序:
Priority Metal
1 Rhodium
2 Platinum
3 Gold
4 Ruthenium
5 Iridium
6 Osmium
7 Palladium
8 Rhenium
9 Silver
10 Indium
我已经使用这段代码整理了一下数据:
newdf.apply(lambda r: sorted(r,reverse = True), axis = 1)
其中将Word_0至4列放置在另一个数据帧(newdf)中,然后以相反的顺序排序,因此空白值最后出现,然后将它们重新连接到包含account_num列的原始数据帧,但是我不知道如何合并自定义列表按照订购顺序。
任何帮助将不胜感激
谢谢
最佳答案
c = pd.Categorical(df2.Metal, df2.Metal, ordered=True)
df.set_index('account_num').transform(lambda k: pd.Categorical(k,
categories=c.categories)\
.sort_values(), axis=1)
产出
Word_0 Word_1 Word_2 Word_3 Word_4
account_num
123 Platinum Osmium Silver NaN NaN
456 Platinum NaN NaN NaN NaN
789 Rhodium Platinum Osmium Silver NaN
当然,总是可以总是
.fillna('')
结束。