Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Apply pandas function to column to create multiple new columns error

For this question i have found this example:

df = pd.DataFrame([[i] for i in range(5)], columns=['num'])
def powers(x):
    return x, x**2, x**3, x**4, x**5, x**6
df['p1'], df['p2'], df['p3'], df['p4'], df['p5'], df['p6'] = zip(*df['num'].apply(powers))
df

i changed the map() function to apply() function, it worked the same.

as you see we have passed a series for the apply() function: zip(*df['num'].apply(powers)).

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

This question’s answer is good, But in my case of study i want to pass a dataFrame to the apply() function as: zip(*df[['num']].apply(powers)) by adding double*double brackets df[['num']] , but i got the following error: ValueError: not enough values to unpack (expected 6, got 3).

i didn’t understand where the mistake is, can you help me please?

>Solution :

In my opinion zip with apply is not recommended combine, for add multiple new columns is possible use:

df = pd.DataFrame([[i] for i in range(5)], columns=['num'])
def powers(x):
    
    return pd.Series([x, x**2, x**3, x**4, x**5, x**6])
df[['p1','p2','p3','p4','p5','p6']] = df['num'].apply(powers)

print (df)
   num  p1  p2  p3   p4    p5    p6
0    0   0   0   0    0     0     0
1    1   1   1   1    1     1     1
2    2   2   4   8   16    32    64
3    3   3   9  27   81   243   729
4    4   4  16  64  256  1024  4096

For pass one column DataFrame is possible use:

df = pd.DataFrame([[i] for i in range(5)], columns=['num'])
def powers(x):
    
    return [x, x**2, x**3, x**4, x**5, x**6]
df[['p1','p2','p3','p4','p5','p6']] = df[['num']].pipe(powers)

print (df)
   num  p1  p2  p3   p4    p5    p6
0    0   0   0   0    0     0     0
1    1   1   1   1    1     1     1
2    2   2   4   8   16    32    64
3    3   3   9  27   81   243   729
4    4   4  16  64  256  1024  4096
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading