python - 如何通过合并两列或多列来创建新列?
问题描述
我创建了一个这样的示例数据框:
A B A+B
0 1 2 3
1 9 60 69
2 20 400 420
我想显示这样的过程:是的,这个过程就像我的最后一个问题,但这次没有滚动窗口的东西
A B A+B Equation
0 1 2 3 1+2
1 9 60 69 9+60 #the expectation
2 20 400 420 20+400
假设 A 列和 B 列是从分离的列创建的,如下所示:
d={'A':[1,9,20],'B':[2,60,400]}
Andhere是我尝试过的一些代码:
df['A+B']=df['A']+df['B']
df['Process']=str(df['A'])+str(df['B'])
这是输出:
A B
0 1 2
1 9 60
2 20 400
A B A+B Process
0 1 2 3 0 1\n1 9\n2 20\nName: A, dtype: int...
1 9 60 69 0 1\n1 9\n2 20\nName: A, dtype: int...
2 20 400 420 0 1\n1 9\n2 20\nName: A, dtype: int... #Is there any step that i missed?
>>>
解决方案
正如亨利建议的那样,实现您想要的最佳方法是:
df['Process'] = df['A'].astype(str) + '+' + df['B'].astype(str)
df
A B A+B Process
0 1 2 3 1+2
1 9 60 69 9+60
2 20 400 420 20+400