Apply function on dataframe Column to get several other columns Pandas Python

Viewed 104

I have a dataframe of thousands of rows. I want to apply a function on a single column in order to get other 7 columns and merge it to the dataframe. Example of Dataframe:

df = pd.DataFrame({'a':[1,2,3],'b':[4,5,6]})
    a   b
0   1   4
1   2   5
2   3   6

Example of Function. The function returns a dataframe

def function(x):
    return pd.DataFrame({'c':[x+2],'d':[x*2],'e':[x%2],'f':[x/2],'g':[x-2],'h':[x**2],'i':[x*x]})

What I try to do and get an error:

df[['c','d','e','f','g','h','i']] = df['a'].apply(lambda x: function(x))

Expected Output:

    a   b   c   d   e   f   g   h   i
0   1   4   3   2   1   0.5 -1  1   1
1   2   5   4   4   0   1.0 0   4   4
2   3   6   5   6   1   1.5 1   9   9
2 Answers

You need remove [] from DataFrame constructor and for processing values in column a like array use DataFrame.pipe:

def function(x):
    return pd.DataFrame({'c':x+2,'d':x*2,'e':x%2,'f':x/2,'g':x-2,'h':x**2,'i':x*x})  


df[['c','d','e','f','g','h','i']] = df['a'].pipe(function)
#alternative
#df[['c','d','e','f','g','h','i']] = function(df['a'])
print (df)
   a  b  c  d  e    f  g  h  i
0  1  4  3  2  1  0.5 -1  1  1
1  2  5  4  4  0  1.0  0  4  4
2  3  6  5  6  1  1.5  1  9  9

Return a pd.Series instead of a pd.DataFrame:

def function(x):
    return pd.DataFrame({'c':[x+2],'d':[x*2],'e':[x%2],'f':[x/2],'g':[x-2],'h':[x**2],'i':[x*x]}).loc[0]

Or,

def function(x):
    return pd.Series({'c':x+2,'d':x*2,'e':x%2,'f':x/2,'g':x-2,'h':x**2,'i':x*x})
Related