0

I have a list of strings stored in a pandas dataframe df, with column name of text (i.e. df['text']). I have a function f(text: str) -> (int, int, int). Now, I want to do the following.

df['a'], df['b'], df['c'] = df['text'].apply(f)

How can I create three columns with the three returned values from the function?

The above code gives the error of

ValueError: too many values to unpack (expected 3)

I tried

df['a', 'b', 'c'] = df['text'].apply(f)

but I get one column with the name of 'a', 'b', 'c'

NB:

  1. There is a similar question in SO, but when I use the following solution from there, I again get an error.
df[['a', 'b', 'c']] = df['text'].apply(f, axis=1, result_type='expand')

The error is

f() got an unexpected keyword argument 'axis'
f() got an unexpected keyword argument 'result_type' #(once I remove the axis=1 parameter)
  1. Note that df has other columns as well
1
  • 1
    Thinking and I have to write - Really thank you for feedback. ;) Commented Jan 23, 2023 at 12:47

1 Answer 1

1

For me your solutions working. But need test if correct return 3 values in tuple.

Here is alternative:

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

def f(x):
    return((x,x+1,x-5))

df[['a', 'b', 'c']] = pd.DataFrame(df['text'].apply(f).tolist(), index=df.index)
print (df)
   text  a  b  c
0     1  1  2 -4
1     2  2  3 -3
2     3  3  4 -2
Sign up to request clarification or add additional context in comments.

3 Comments

It works, but 1. I get the following warning. 2. Can you give an overview of what is going on, what the tolist() and index=df.index does.
@berinaniesh - First warning - before my solution i not some filtering? Like df = df[df['col'] > 10] ? If yes, for avoid it use copy like df = df[df['col'] > 10].copy()
@berinaniesh - For list of tuples is used tolist() function and then for DataFrame with same index values is pass df.index. It is necessary, if original dataframe has different indices.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.