繁体   English   中英

嵌套np.where语句的替代方案,用于在基于其他两个现有列创建新的pandas布尔列时保留NaN值

[英]Alternative to nested np.where statements to retain NaN values while creating a new pandas boolean column based on two other existing columns

我试图找出一种更直接的替代方法,用于基于另外两个包含True,False或NaN值的列在pandas数据框中评估和创建新列。 我希望新列相对于两个参考列的评估如下:

  • 如果为真->真
  • 如果至少有一个False而不是True-> False
  • 如果两者均为NaN-> NaN

我已经找到了使用几个嵌套的np.where语句的解决方案,但希望使用更直接的方法。 对于单个参考列,我知道了如何执行此操作(请参见下面的col4),但无法确定是否有一种方法可以将其适应多个参考列。

当前解决方案:

import pandas as pd
import numpy as np

d = {'col1': [True, True, True, False, False, False, np.nan, np.nan, np.nan],
     'col2': [True, False, np.nan,True, False, np.nan,True, False, np.nan]}
df = pd.DataFrame(data=d)

df['col3'] = np.where(
    pd.notnull(df['col1']) & pd.notnull(df['col2']),
    (df['col1'] == True) | (df['col2'] == True),
    np.where(
        pd.isnull(df['col1']) & pd.isnull(df['col2']),
        np.nan,
        np.where(pd.notnull(df['col1']),df['col1'],df['col2'])
    )
)

单参考柱解决方案:

df['col4'] = df['col1'].map(lambda x: x, na_action='ignore')

np.select()用于这种类型的作业:

df['col3'] = pd.Series(np.select(
    [(df.col1 == True) | (df.col2 == True), (df.col1 == False) | (df.col2 == False)],
    [True, False], np.array(np.nan, object)))

或者,仅使用熊猫,但我认为这种方式的可读性较差:

df['col3'] = df.col1.where(df.col1, df.col2.where(df.col2.notnull(), df.col1))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM