[python] 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.

This question is related to python python-2.7 pandas

The answer is


Concerning n00b's comment: "I get the following warning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead"

I was getting the same error. In my case it was because I was trying to perform the column addition on a dataframe that was created like this:

df_b = df[['colA', 'colB', 'colC']]

instead of:

df_c = pd.DataFrame(df, columns=['colA', 'colB', 'colC'])

df_b is a copy of a slice from df
df_c is an new dataframe. So

df_c['colD'] = df['colA'] + df['colB']+ df['colC']

will add the columns and won't raise any warning. Same if .sum(axis=1) is used.


Can do using loc

In [37]:  df = pd.DataFrame({"A":[1,2,3],"B":[4,6,9]})

In [38]: df
Out[38]:
   A  B
0  1  4
1  2  6
2  3  9

In [39]: df['C']=df.loc[:,['A','B']].sum(axis=1)

In [40]: df
Out[40]:
   A  B   C
0  1  4   5
1  2  6   8
2  3  9  12

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)

I wanted to add a comment responding to the error message n00b was getting but I don't have enough reputation. So my comment is an answer in case it helps anyone...

n00b said:

I get the following warning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead

He got this error because whatever manipulations he did to his dataframe prior to creating df['C'] created a view into the dataframe rather than a copy of it. The error didn't arise form the simple calculation df['C'] = df['A'] + df['B'] suggested by DeepSpace.

Have a look at the Returning a view versus a copy docs.


You could use sum function to achieve that as @EdChum mentioned in the comment:

df['C'] =  df[['A', 'B']].sum(axis=1)

In [245]: df
Out[245]: 
   A  B   C
0  1  4   5
1  2  6   8
2  3  9  12

You could do:

df['C'] = df.sum(axis=1)

If you only want to do numerical values:

df['C'] = df.sum(axis=1, numeric_only=True)

The simplest way would be to use DeepSpace answer. However, if you really want to use an anonymous function you can use apply:

df['C'] = df.apply(lambda row: row['A'] + row['B'], axis=1)

As of Pandas version 0.16.0 you can use assign as follows:

df = pd.DataFrame({"A": [1,2,3], "B": [4,6,9]})
df.assign(C = df.A + df.B)

# Out[383]: 
#    A  B   C
# 0  1  4   5
# 1  2  6   8
# 2  3  9  12

You can add multiple columns this way as follows:

df.assign(C = df.A + df.B,
          Diff = df.B - df.A,
          Mult = df.A * df.B)
# Out[379]: 
#    A  B   C  Diff  Mult
# 0  1  4   5     3     4
# 1  2  6   8     4    12
# 2  3  9  12     6    27

You can solve it by adding simply: df['C'] = df['A'] + df['B']


Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to python-2.7

Numpy, multiply array with scalar Not able to install Python packages [SSL: TLSV1_ALERT_PROTOCOL_VERSION] How to create a new text file using Python Could not find a version that satisfies the requirement tensorflow Python: Pandas pd.read_excel giving ImportError: Install xlrd >= 0.9.0 for Excel support Display/Print one column from a DataFrame of Series in Pandas How to calculate 1st and 3rd quartiles? How can I read pdf in python? How to completely uninstall python 2.7.13 on Ubuntu 16.04 Check key exist in python dict

Examples related to pandas

xlrd.biffh.XLRDError: Excel xlsx file; not supported Pandas Merging 101 How to increase image size of pandas.DataFrame.plot in jupyter notebook? Trying to merge 2 dataframes but get ValueError Python Pandas User Warning: Sorting because non-concatenation axis is not aligned How to show all of columns name on pandas dataframe? Pandas/Python: Set value of one column based on value in another column Python Pandas - Find difference between two data frames Pandas get the most frequent values of a column Python convert object to float