从2个不同的数据框熊猫中添加两列的值

时间:2019-03-07 07:18:49

标签: python pandas dataframe

我想根据名称相同的条件添加2个不同数据框的2列:

import pandas as pd
df1 = pd.DataFrame([("Apple",2),("Litchi",4),("Orange",6)], columns=['a','b'])
df2 = pd.DataFrame([("Apple",200),("Orange",400),("Litchi",600)], columns=['a','c'])

现在我想添加b和c列(如果名称与a相同)。

我尝试了此df1['b+c']=df1['b']+df2['c'],但它只是添加了列b和c,因此结果为

      a    b  b+c
0   Apple  2  202
1  Litchi  4  404
2  Orange  6  606

但我想

    a  b+c
0   Apple  202
1  Litchi  604
2  Orange  406

我想我必须使用isin,但我不知道如何使用?

1 个答案:

答案 0 :(得分:1)

在求和运算中,列bc由索引值对齐,因此必须由列a的{​​{3}}创建索引:

s1 = df1.set_index('a')['b']
s2 = df2.set_index('a')['c']
df1 = (s1+s2).reset_index(name='b+c')
print (df1)
        a  b+c
0   Apple  202
1  Litchi  604
2  Orange  406

编辑:如果需要原始值用于不匹配的值,请使用带有参数fill_value=0的{​​{3}}

df2 = pd.DataFrame([("Apple",200),("Apple",400),("Litchi",600)], columns=['a','c']) 
print (df2)
        a    c
0   Apple  200
1   Apple  400
2  Litchi  600

s1 = df1.set_index('a')['b']
s2 = df2.set_index('a')['c']
df1 = s1.add(s2, fill_value=0).reset_index(name='b+c')
print (df1)
        a    b+c
0   Apple  202.0
1   Apple  402.0
2  Litchi  604.0
3  Orange    6.0
相关问题