Skip to content Skip to sidebar Skip to footer

Create Multiple New Columns For Pandas Dataframe With Apply + Function

I have a pandas dataframe df of the following shape: (763, 65) I use the following code to create 4 new columns: df[['col1', 'col2', 'col3','col4']] = df.apply(myFunc, axis=1) def

Solution 1:

Demo:

In [40]: df = pd.DataFrame({'a':[1,2,3]})

In [41]: df
Out[41]:
   a
0  1
1  2
2  3

In [42]: def myFunc(row):
    ...:     #code to get some result from another dataframe
    ...:     # NOTE: trick is to return pd.Series()
    ...:     return pd.Series([1,2,3,4]) * row['a']
    ...:

In [44]: df[['col1', 'col2', 'col3','col4']] = df.apply(myFunc, axis=1)

In [45]: df
Out[45]:
   a  col1  col2  col3  col4
0  1     1     2     3     4
1  2     2     4     6     8
2  3     3     6     9    12

Disclaimer: try to avoid using .apply(..., axis=1) - as it's a for loop under the hood - i.e. it's not vectoried and will work much slower compared to vectorized Pandas/Numpy ufuncs.

PS if you would provide details of what you are trying to calculate in the myFunc functuion, then we could try to find a vectorized solution...

Post a Comment for "Create Multiple New Columns For Pandas Dataframe With Apply + Function"