简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM