Pandas list comprehension tuple from dataframe

孤人 提交于 2020-06-08 20:01:21

问题


This is just a nitpicking syntactic question...

I have a dataframe, and I want to use list comprehension to evaluate a function using lots of columns.

I know I can do this

df['result_col'] = [some_func(*var) for var in zip(df['col_1'], df['col_2'],... ,df['col_n'])]

I would like to do something like this

df['result_col'] = [some_func(*var) for var in zip(df[['col_1', 'col_2',... ,'col_n']])]

i.e. not having to write df n times. I cannot for the life of me figure out the syntax.


回答1:


this should work, but honestly, OP figured it himself as well, so +1 OP :)

df['result_col'] = [some_func(*var) for var in zip(*[df[col] for col in ['col_1', 'col_2',... ,'col_n']])]



回答2:


As mentioned in the comments above, you should use apply instead:

df['reult_col'] = df.apply(lambda x: some_func(*tuple(x.values)), axis=1)



回答3:


# print 3rd col
def some_func(row):
    print(row[2])


df['result_col'] = [some_func(*row) for row in zip(df[['col_1', 'col_2',... ,'col_n']].to_numpy())]

or

# print 3rd col
def some_func(row):
    print(row[2])

df['result_col'] = [some_func(row[0]) for row in zip(df[['col_1', 'col_2',... ,'col_n']].to_numpy())]

or

# print 3rd col
def some_func(x):
    print(x)

df['result_col'] = [some_func(row[0][2]) for row in zip(df[['col_1', 'col_2',... ,'col_n']].to_numpy())]

See also:

  • Memory efficient way for list comprehension of pandas dataframe using multiple columns
  • list comprehension in pandas


来源:https://stackoverflow.com/questions/52607864/pandas-list-comprehension-tuple-from-dataframe

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