Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make new column in Panda dataframe by adding values from other columns

I have a dataframe with values like

A B 1 4 2 6 3 9 

I need to add a new column by adding values from column A and B, like

A B C 1 4 5 2 6 8 3 9 12 

I believe this can be done using lambda function, but I can't figure out how to do it.

like image 211
n00b Avatar asked Dec 01 '15 15:12

n00b


People also ask

How will you create a new column whose value is calculated from two other columns?

To create a new column, use the [] brackets with the new column name at the left side of the assignment.

How do you populate a column based on two columns values in a DataFrame?

Create New Columns in Pandas DataFrame Based on the Values of Other Columns Using the DataFrame. apply() Method. It applies the lambda function defined in the apply() method to each row of the DataFrame items_df and finally assigns the series of results to the Final Price column of the DataFrame items_df .


2 Answers

Very simple:

df['C'] = df['A'] + df['B'] 
like image 51
DeepSpace Avatar answered Oct 11 '22 13:10

DeepSpace


Building a little more on Anton's answer, you can add all the columns like this:

df['sum'] = df[list(df.columns)].sum(axis=1) 
like image 21
sparrow Avatar answered Oct 11 '22 14:10

sparrow