python - 从 pandas 的 2 个数据框中添加 2 列

标签 python pandas dataframe

我是 Pandas 新手,亲爱的,你能帮我解决这个问题吗? 我有 2 个 DF:

df1 = pd.DataFrame({'A': ['name', 'color', 'city', 'animal'], 'number': ['1', '32', '22', '13']})

df2 = pd.DataFrame({'A': ['name', 'color', 'city', 'animal'], 'number': ['12', '2', '42', '15']})

df1
    A       number
0   name    1
1   color   32
2   city    22
3   animal  13
DF1
    A       number
0   name    12
1   color   2
2   city    42
3   animal  15

我需要获取列号的总和,例如

DF1
    A       number
0   name    13
1   color   34
2   city    64
3   animal  27

但是如果我这样做 new = df1 + df2 我会得到

NEW
    A             number
0   namename        13
1   colorcolor      34
2   citycity        64
3   animalanimal    27

我什至尝试过合并=“A”,但什么也没有。 谁能告诉我吗 谢谢

最佳答案

这里有两种不同的方式:一种是 add ,以及一个带有 concatgroupby 的组合。无论哪种情况,您都需要确保您的 number 列首先是数字(您的示例数据帧具有字符串):

# set `number` to numeric (could be float, I chose int here)
df1['number'] = df1['number'].astype(int)
df2['number'] = df2['number'].astype(int)

# method 1, set the index to `A` in each and add the two frames together:
df1.set_index('A').add(df2.set_index('A')).reset_index()

# method 2, concatenate the two frames, groupby A, and get the sum:
pd.concat((df1,df2)).groupby('A',as_index=False).sum()

输出:

        A  number
0  animal      28
1    city      64
2   color      34
3    name      13

关于python - 从 pandas 的 2 个数据框中添加 2 列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53698112/

相关文章:

python - 计算一个单词中出现的字母到 pandas DataFrame

python - PostgreSQL 无法创建 plpythonu 扩展

python - Pandas 数据框中的分组加权平均值和总和

python - 为什么我会收到这个(显然)不寻常的 AttributeError : 'bytes' object has no attribute '_all_strings' ? 有没有办法解决它?

Python bcolz 如何合并两个 ctables

python - 从 Pandas 长格式创建事件图

python - 根据另一列中的值删除一列的重复项,Python,Pandas

string - 如何在 Julia 中使用字符串命名数据框中的列?

python - 以简单且 Python 的方式将简单的字典写入 csv 文件?

python - 更改Python中列表的起始索引?