1
import pandas as pd
import numpy as np

def ced(x):
    return x+1, x+2, x+3


df = pd.DataFrame(data=[[1,2],[10,20]], columns=['a','b'])


df['x'], df['y'], df['z'] = df['a'].apply(lambda x: ced(x)) 


print(df)

error:

line 11, in df['x'], df['y'], df['z'] = df['a'].apply(lambda x: ced(x)) ValueError: not enough values to unpack (expected 3, got 2)

this thing works for

import pandas as pd
import numpy as np

def ced(x):
    return x+1, x+2


df = pd.DataFrame(data=[[1,2],[10,20]], columns=['a','b'])


df['x'], df['y'] = df['a'].apply(lambda x: ced(x)) 


print(df)

output:

    a   b  x   y
0   1   2  2  11
1  10  20  3  12

I don't know what is the problem here.

1 Answer 1

1

I suggest change function for return Series and subset of new columns:

def ced(x):
    return pd.Series([x+1, x+2, x+2])

df = pd.DataFrame(data=[[1,2],[10,20]], columns=['a','b'])


df[['x','y', 'z']] = df['a'].apply(lambda x: ced(x)) 

print(df)
    a   b   x   y   z
0   1   2   2   3   3
1  10  20  11  12  12

Another solution is create DataFrame by constructor:

def ced(x):
    return x+1, x+2, x+2

df = pd.DataFrame(data=[[1,2],[10,20]], columns=['a','b'])


df[['x','y', 'z']] = pd.DataFrame(df['a'].apply(lambda x: ced(x)).values.tolist())
print(df)
    a   b   x   y   z
0   1   2   2   3   3
1  10  20  11  12  12
Sign up to request clarification or add additional context in comments.

4 Comments

can you tell which one will be faster first one or the second for large dataframe?
@Nihal - I think second one.
@Nihal - Just tested In [260]: %timeit df[['x','y', 'z']] = pd.DataFrame(df['a'].apply(lambda x: ced(x)).values.tolist()) 3.05 ms ± 99.1 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) In [262]: %timeit df[['x','y', 'z']] = df['a'].apply(lambda x: ced(x)) 349 ms ± 8.56 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
with df = pd.concat([df] * 1000, ignore_index=True)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.