首页 > 解决方案 > Pandas DataFrame)一列替换其他df

问题描述

我有两个熊猫数据框

# python 3
one is | A | B | C | and another is | D | E | F |
       |---|---|---|                |---|---|---|
       | 1 | 2 | 3 |                | 3 | 4 | 6 |
       | 4 | 5 | 6 |                | 8 | 7 | 9 |
       | ......... |                | ......... |

我想得到“预期”的结果

expected result : 

       | A | D | E | F | C |               
       |---|---|---|---|---|               
       | 1 | 3 | 4 | 6 | 3 |               
       | 4 | 8 | 7 | 9 | 6 |               
       | ................. |
        
df1['B'] convert into df2

       

我努力了

pd.concat([df1,df2], axis=1, sort=False)

and drop column df['B']

但它似乎效率不高。可以通过使用 insert() 或其他方法解决吗?

标签: pythonpandasdataframereplaceconcatenation

解决方案


我认为您的方法很好,您也可以删除之前的列concat

pd.concat([df1.drop('B', axis=1),df2], axis=1, sort=False)

另一种方法DataFrame.join

df1.drop('B', axis=1).join(df2)

推荐阅读