Assign values to multiple columns using DataFrame.assign()

Question:

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
Asked By: berinaniesh

||

Answers:

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
Answered By: jezrael
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.