Reputation: 1034
Given a function
that takes multiple arguments and returns multiple values as so:
def tuple_unpack(value, another_value):
''' does some interesting stuff ... '''
return value, another_value
Is there a way to apply such function to a pandas
dataframe
where for the 2 function arguments I can pass values from 2 columns, then unpack the output tuple on multiple colums as so:
df[['value_col','another_value_col']] = df.apply(lambda df.col, df.col: tuple_unpack)
Upvotes: 4
Views: 2417
Reputation: 381
I would use the following
df['value_col'], df['another_value_col'] = df.apply(lambda x: tuple_unpack(x.col_1, x.col_2), axis=1, result_type='expand').T.values
Upvotes: 0
Reputation: 323226
You can using concat
, with dataframe constructor
unpackdf=pd.DataFrame(df.apply(lambda x : tuple_unpack(x.col_1,x.col_2),1).tolist(),columns=['col1','col2'],index=df.index)
yourdf=pd.concat([unpackdf,df],axis=1)
Upvotes: 4