我是 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 我会得到 p>
NEW
A number
0 namename 13
1 colorcolor 34
2 citycity 64
3 animalanimal 27
我什至尝试过合并=“A”,但什么也没有。 谁能告诉我吗 谢谢
最佳答案
这里有两种不同的方式:一种是 add
,以及一个带有 concat
和 groupby
的组合。无论哪种情况,您都需要确保您的 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/