【问题标题】:python lamba - if statement with conditions in multiple columnspython lambda - if 语句在多列中具有条件
【发布时间】:2020-03-28 00:33:39
【问题描述】:

我有一个数据框:

df = pd.DataFrame({'col1': [1,2,3,4,5], 'col2':[1,2,3,4,5], 'col3':['a','b','c','d','e']})

我想创建一个新列,如果 col1 和 col2 等于 1,则它会说“是”,否则它会说“否”。

我尝试过使用 lambda 函数但没有成功:

df['win'] = df[['col1', 'col2']].apply(lambda x: 'Yes' if (x['col1'] == 1) & (x['col2'] == 1) else 'No')

有没有更好的方法来做到这一点?或对我所做的事情进行改进,使其有效。

【问题讨论】:

  • 虽然你不应该对这个操作使用apply,但逻辑上你的apply是正确的。但是,您需要添加 axis=1 作为参数,以便它知道逐行缓慢地进行计算:(

标签: python pandas


【解决方案1】:

是的,您可以使用np.where

import pandas as pd
import numpy as np

df = pd.DataFrame({'col1': [1,2,3,4,5], 'col2':[1,2,3,4,5], 'col3':['a','b','c','d','e']})

condition = ((df['col1'] == 1) & (df['col2'] == 1))
# Return 'Yes' if the condition is True, and 'No' if False
df['win'] = np.where(condition, 'Yes', 'No')

【讨论】:

    【解决方案2】:

    您可以检查两列是否等于1,并执行逐行,然后执行到YesNo 的映射:

    df['win'] = df[['col1', 'col2']].eq(1).all(axis=1).replace({True: 'Yes', False: 'No'})
    

    对于大型数据帧,这将更快,因为它的操作是“批量”完成的。

    【讨论】:

      【解决方案3】:

      最好为它创建一个函数,而不是在轴 1 上应用 lambda:

      def yes_no(x):
       if (x['col1'] == 1) & (x['col2'] == 1):
         return 'Yes'
       else:
         return 'No'
      

      然后在axis = 1上应用lambda:

      df['win'] = df.apply(lambda x: yes_no(x), axis = 1)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-10-20
        • 1970-01-01
        • 2023-03-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-06-20
        相关资源
        最近更新 更多