Python 如何在另一个数据帧中替换具有相同名称的列?

Python 如何在另一个数据帧中替换具有相同名称的列?,python,python-2.7,pandas,Python,Python 2.7,Pandas,我有以下大熊猫数据帧A: A B ... C cat cotsco... apple cat walmart... google dog sears... google dog homemart... amazon ... fish walmart... microsoft 数据帧B: A B ... D 1.2 0.0 ... 1 3.3 9.1 ... 2 4.5 1.2 ... 5 6.79 1.222 ... 4

我有以下大熊猫数据帧A:

A     B    ...   C
cat   cotsco... apple
cat   walmart... google
dog   sears...   google
dog   homemart... amazon
...
fish  walmart... microsoft
数据帧B:

A    B ...     D
1.2  0.0  ...  1
3.3  9.1 ...   2
4.5  1.2 ...   5
6.79 1.222 ... 4
...
9.9  1.3 ...   8
如何替换B中数据帧A中具有相同名称的所有列

A     B    ...      C     D
cat   cotsco...   apple   1
cat   walmart...  google  2
dog   sears...    google  5
dog   homemart... amazon  4
...
fish  walmart... microsoft 8
我知道我可以做
df1['D']=df2['D']
。然而,我有2000个这样的专栏。还有其他简便的方法吗?

仅使用分配:

df1['D'] = df2['D']
如果需要添加多个具有不同列名称的列:

df = pd.concat([df1, df2[df2.columns.difference(df1.columns)]], axis=1)
或:


谢谢我已经试过了。。。然而,我不能在所有情况下用手书写……你能解释一下为什么这个解决方案不起作用吗?谢谢。这个解决方案不起作用,因为我有2000个这样的专栏。。。我无法手工编写所有2000个案例。对于第二个案例,我得到了:keyrerror:“索引(['A'...'B'],\n dtype='object')不在索引中”oops,我更改了解决方案,请检查它-首先我将df1.columns与df2.column交换,抱歉。现在它起作用了。
df = df1.join(df2[df2.columns.difference(df1.columns)])