追加到Pandas中的DataFrame作为新列

The*_*ark 4 python pandas

我有两个具有相同索引的DataFrame,并希望将第二个追加到第一个。可以说我有:

df1 = pd.DataFrame([1,2,3], index = [2,3,4])
df2 = pd.DataFrame([3,5,3], index = [2,3,4])
df1 = df1.append(df2)
Run Code Online (Sandbox Code Playgroud)

哪个返回

   0
2  1
3  2
4  3
2  3
3  5
4  3
Run Code Online (Sandbox Code Playgroud)

但是我希望它在索引匹配的地方添加一个新列:

2  1  3
3  2  5
4  3  3
Run Code Online (Sandbox Code Playgroud)

有没有办法做到这一点?

EdC*_*ica 5

使用concat并传递参数axis=1以列方式连接dfs列表:

In [3]:

df1 = pd.DataFrame([1,2,3], index = [2,3,4])
df2 = pd.DataFrame([3,5,3], index = [2,3,4])
pd.concat([df1,df2], axis=1)
Out[3]:
   0  0
2  1  3
3  2  5
4  3  3
Run Code Online (Sandbox Code Playgroud)

您也可以使用,join但必须先重命名该列:

In [6]:

df1.join(df2.rename(columns={0:'x'}))
Out[6]:
   0  x
2  1  3
3  2  5
4  3  3
Run Code Online (Sandbox Code Playgroud)

merge指定您希望匹配的索引:

In [8]:

df1.merge(df2.rename(columns={0:'x'}), left_index=True, right_index=True )
Out[8]:
   0  x
2  1  3
3  2  5
4  3  3
Run Code Online (Sandbox Code Playgroud)