Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add 2 new columns to existing dataframe using apply

I want to use the apply function that: - Takes 2 columns as inputs - Outputs two new columns based on a function.

An example is with this add_multiply function.

#function with 2 column inputs and 2 outputs
def add_multiply (a,b):
  return (a+b, a*b )

#example dataframe
df = pd.DataFrame({'col1': [1, 2], 'col2': [3, 4]})

#this doesn't work
df[['add', 'multiply']] = df.apply(lambda x: add_multiply(x['col1'], x['col2']), axis=1)

ideal result:

col1  col2  add  multiply
1     3     4    3
2     4     6    8

like image 908
Leo Avatar asked Aug 25 '19 13:08

Leo


People also ask

How do you add two columns in a data frame?

Select each column of DataFrame df through the syntax df["column_name"] and add them together to get a pandas Series containing the sum of each row. Create a new column in the DataFrame through the syntax df["new_column"] and set it equal to this Series to add it to the DataFrame.

How do I add more columns in pandas?

In pandas you can add/append a new column to the existing DataFrame using DataFrame. insert() method, this method updates the existing DataFrame with a new column. DataFrame. assign() is also used to insert a new column however, this method returns a new Dataframe after adding a new column.


1 Answers

You can add result_type='expand' in the apply:

‘expand’ : list-like results will be turned into columns.

df[['add', 'multiply']]=df.apply(lambda x: add_multiply(x['col1'], x['col2']),axis=1,
                             result_type='expand')

Or call a dataframe constructor:

df[['add', 'multiply']]=pd.DataFrame(df.apply(lambda x: add_multiply(x['col1'], 
                                    x['col2']), axis=1).tolist())

   col1  col2  add  multiply
0     1     3    4         3
1     2     4    6         8
like image 189
anky Avatar answered Oct 12 '22 09:10

anky