list comprehension in pandas

后端 未结 4 907
难免孤独
难免孤独 2020-12-16 07:36

I\'m giving a toy example but it will help me understand what\'s going on for something else I\'m trying to do. Let\'s say I want a new column in a dataframe \'optimal_fruit

4条回答
  •  太阳男子
    2020-12-16 08:03

    If you do not want to repeat df2 for each column:

    [row[0][0]*row[0][1]-row[0][2] for row in zip(df2[['apples', 'oranges', 'bananas']].to_numpy())]
    

    or

    def func(row):
        print(row[0]*row[1]-row[2])
    
    [func(*row) for row in zip(df2[['apples', 'oranges', 'bananas']].to_numpy())]
    

    See also:

    • Memory efficient way for list comprehension of pandas dataframe using multiple columns
    • Dataframe list comprehension "zip(...)": loop through chosen df columns efficiently with just a list of column name strings

    EDIT:

    Please use df.iloc and df.loc instead of df[[...]], see Selecting multiple columns in a pandas dataframe

提交回复
热议问题