我有一些数据,例如
>>> df1
Col1 Col2
0 Hi Hello
1 How Fine
2 Why Because
3 You Me
4 We They
>>> df2
Col1 Col2
0 Mr Mrs
1 Welcome Bye
2 Wow Ohh
3 Sit Stand
我只希望连接这两个数据帧的第一列Col1
,并更新df1
,而使Col2
保持不变,但我无法做到
我尝试了很多方法,但没有成功
我想要的输出
>>> df2
Col1 Col2
0 Hi Hello
1 How Fine
2 Why Because
3 You Me
4 We They
5 Mr
6 Welcome
7 Wow
8 Sit
索引不同还是出现NaN而不是空单元格都没关系
我尝试过的事情
1
>>> r=pd.concat([df1["Col1"],df2["Col1"]])
>>> df1["Col1"] = r.reset_index(drop=True)
>>> df1
Col1 Col2
0 Hi Hello
1 How Fine
2 Why Because
3 You Me
4 We They
2
>>> pd.concat([df1["Col1"],df2])
0 Col1 Col2
0 Hi NaN NaN
1 How NaN NaN
2 Why NaN NaN
3 You NaN NaN
4 We NaN NaN
0 NaN Mr Mrs
1 NaN Welcome Bye
2 NaN Wow Ohh
3 NaN Sit Stand
3
I Tried append(), merge() and some more techniques but failed
答案 0 :(得分:3)
append
df1.append(df2[['Col1']])
Col1 Col2
0 Hi Hello
1 How Fine
2 Why Because
3 You Me
4 We They
0 Mr NaN
1 Welcome NaN
2 Wow NaN
3 Sit NaN
concat
pd.concat([df1, df2[['Col1']]])
Col1 Col2
0 Hi Hello
1 How Fine
2 Why Because
3 You Me
4 We They
0 Mr NaN
1 Welcome NaN
2 Wow NaN
3 Sit NaN
无论哪种情况,您都可以通过ignore_index=True
选项忽略索引。
df1.append(df2[['Col1']], ignore_index=True)
Col1 Col2
0 Hi Hello
1 How Fine
2 Why Because
3 You Me
4 We They
5 Mr NaN
6 Welcome NaN
7 Wow NaN
8 Sit NaN