PostJavanese
PostJavanese

Reputation: 85

How to create a new column from merging two or more column?

I created a sample data frame like this:

     A   B    A+B
0    1   2    3
1    9   60   69
2    20  400  420

And i want to display the process like this: Yeah the process like my last question but without rolling window stuff this time

     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

Assuming column A and Column B is created from separated columns like this:

d={'A':[1,9,20],'B':[2,60,400]}

Andhere's some code that i tried:

df['A+B']=df['A']+df['B']

df['Process']=str(df['A'])+str(df['B'])

Here's the output:

    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?
>>>

Upvotes: 1

Views: 57

Answers (2)

Marcelo Graef
Marcelo Graef

Reputation: 101

You can use Apply function

df['Process']= df.apply(lambda row : f"{row['A']}+{row['B']}", axis=1)

It works for me.

Upvotes: 0

Arvind Kumar
Arvind Kumar

Reputation: 451

As Henry suggested, the best way to achieve what you want is:

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

Upvotes: 1

Related Questions