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:
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)
df
has other columns as wellFor 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.