Pandas apply tuple unpack function on multiple columns

时间秒杀一切 提交于 2019-12-14 02:08:47

问题


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)  

回答1:


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)


来源:https://stackoverflow.com/questions/52876635/pandas-apply-tuple-unpack-function-on-multiple-columns

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!