假设我必须进行数据帧处理,如下所示:
df=pd.DataFrame({'a':[1,4,3,2],'b':[1,2,3,4]})
df2=pd.DataFrame({'a':[1,2,3,4],'b':[1,2,3,4],'c':[34,56,7,55]})
我想按
df
列上的df2
数据顺序对'a'
数据进行排序,因此df.a
列将是df2.a
的顺序,并使整个数据帧都保持该顺序。所需的输出:
a b
0 1 1
1 2 4
2 3 3
3 4 2
(手动制作,如果有任何错误,请告诉我:D)
我自己的尝试:
df = df.set_index('a')
df = df.reindex(index=df2['a'])
df = df.reset_index()
print(df)
符合预期!!!,
但是当我有更长的数据帧时,例如:
df=pd.DataFrame({'a':[1,4,3,2,3,4,5,3,5,6],'b':[1,2,3,4,5,5,5,6,6,7]})
df2=pd.DataFrame({'a':[1,2,3,4,3,4,5,6,4,5],'b':[1,2,4,3,4,5,6,7,4,3]})
它不能正常工作。
注意:我不仅要解释原因,还需要针对大数据帧的解决方案
最佳答案
一种可能的解决方案是在两个DataFrame
中创建帮助程序列,因为值重复:
df['g'] = df.groupby('a').cumcount()
df2['g'] = df2.groupby('a').cumcount()
df = df.set_index(['a','g']).reindex(index=df2.set_index(['a','g']).index)
print(df)
b
a g
1 0 1.0
2 0 4.0
3 0 3.0
4 0 2.0
3 1 5.0
4 1 5.0
5 0 5.0
6 0 7.0
4 2 NaN
5 1 6.0
或者可能需要
merge
:df3 = df.merge(df2[['a','g']], on=['a','g'])
print(df3)
a b g
0 1 1 0
1 4 2 0
2 3 3 0
3 2 4 0
4 3 5 1
5 4 5 1
6 5 5 0
7 5 6 1
8 6 7 0
关于python - 在一列上按另一列对数据框进行排序-Pandas,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53627976/