如何基于具有相同列但顺序不同的另一个数据帧对列进行重新排序 [英] How to re-order the columns based on another dataframe with the same columns but different order
本文介绍了如何基于具有相同列但顺序不同的另一个数据帧对列进行重新排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想知道是否有一种方便的方法可以根据具有相同列但顺序不同的另一列来对数据框的列进行排序.还是我必须做一个循环才能实现这一目标?
I wonder if there is a handy method to order the columns of a dataframe based on another one that has the same columns but with different order. Or, do I have to make a loop to achieve this?
推荐答案
尝试一下:
df2 = df2[df1.columns]
演示:
In [1]: df1 = pd.DataFrame(np.random.randint(0, 10, (5,4)), columns=list('abcd'))
In [2]: df2 = pd.DataFrame(np.random.randint(0, 10, (5,4)), columns=list('badc'))
In [3]: df1
Out[3]:
a b c d
0 8 3 9 6
1 0 6 4 7
2 7 2 0 7
3 0 5 1 8
4 6 2 5 4
In [4]: df2
Out[4]:
b a d c
0 3 8 0 4
1 7 7 4 2
2 2 7 3 8
3 2 4 9 6
4 3 4 7 1
In [5]: df2 = df2[df1.columns]
In [6]: df2
Out[6]:
a b c d
0 8 3 4 0
1 7 7 2 4
2 7 2 8 3
3 4 2 6 9
4 4 3 1 7
替代解决方案:
df2 = df2.reindex_axis(df1.columns, axis=1)
注意:自版本0.21.0起,不再支持熊猫reindex_axis
:请改用reindex.
Note: Pandas reindex_axis
is deprecated since version 0.21.0: Use reindex instead.
df2 = df2.reindex(df1.columns, axis=1)
这篇关于如何基于具有相同列但顺序不同的另一个数据帧对列进行重新排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文