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

Assign values to multiple columns using DataFrame.assign()

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

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

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 we remove the axis=1 parameter)
  1. Note that df has other columns as well

>Solution :

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
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