在Pandas中将新列附加到DataFrame中

5

我有两个索引相同的数据框,想要将第二个添加到第一个上面。可以假设我有:

df1 = pd.DataFrame([1,2,3], index = [2,3,4])
df2 = pd.DataFrame([3,5,3], index = [2,3,4])
df1 = df1.append(df2)

该函数返回

   0
2  1
3  2
4  3
2  3
3  5
4  3

但我希望它能添加一个新的列,其中索引匹配:
2  1  3
3  2  5
4  3  3

有没有办法做到这一点?


2个回答

8
使用concat函数并传递参数axis=1,按列将数据框列表拼接起来:
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

您也可以使用join,但您需要先重命名列:

In [6]:

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

或者使用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

1
如果索引完全匹配,而另一个DataFrame只有一列(就像你的问题一样),那么你甚至可以将另一个DataFrame添加为新列。
>>> df1['new_column'] = df2
>>> df1
   0  new_column
2  1           3
3  2           5
4  3           3

一般而言,“concat”方法更好。如果您有不同的索引,可以选择进行“inner join”或“outer join”。
>>> df2 = pd.DataFrame([3,5,3], index = [2,3,5])
>>> df2
   0
2  3
3  5
5  3

>>> pd.concat([df1, df2], axis=1, join='inner')
   0  0
2  1  3
3  2  5

>>> pd.concat([df1, df2], axis=1, join='outer')
    0   0
2   1   3
3   2   5
4   3 NaN
5 NaN   3

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接