【问题标题】:How to do conditional statements in pandas/python with null values如何在 pandas/python 中使用空值执行条件语句
【发布时间】:2016-12-28 08:26:46
【问题描述】:

如何在 pandas 中进行条件替换?

df = pd.DataFrame([[1, 2, 3], [4, None, None], [None, None, 9]])

在 R 中 - 认为这段代码很容易理解:

library(dplyr)
df = df %>% 
mutate(   #   mutate means create new column for non-r people
my_new_column = ifelse( is.na(the_2nd_column)==TRUE & is.na(the_3rd_column)==TRUE, ' abc', 'cuz')

如何在 pandas 中执行此操作 - 可能是语法上的愚蠢问题,但我听说 np.where 相当于 R 中的 if else ...

df['new_column'] = np.where(np.nan(....help here with a conditional....))

【问题讨论】:

    标签: python pandas numpy if-statement null


    【解决方案1】:

    np.where这样的

    df['new_column'] = np.where(df[1].isnull() & df[2].isnull(), 'abc', 'cuz')
    print(df)
    

    更多的 numpy 或更快

    df['new_column'] = \
        np.where(np.isnan(df[1].values) & np.isnan(df[2].values), 'abc', 'cuz')
    
    
         0    1    2 new_column
    0  1.0  2.0  3.0        cuz
    1  4.0  NaN  NaN        abc
    2  NaN  NaN  9.0        cuz
    

    时机

    【讨论】:

    • 你能把时间按升序排列吗?中间有一个208us,应该会上升。 :D :P 呵呵
    • 谢谢你这个作品 - 尤其是空.....版本但是如果你不介意我有一个问题。如果我是两个附加两个数据集以及 1 个数据集中存在的 1 列,而另一个数据集中不存在 - is nan 版本会导致错误消息,而 is null 版本有效。似乎 null 对错误更健壮。
    • 或许用更大的数据集进行基准测试会更好吗?
    【解决方案2】:

    使用np.where

    In [279]: df['new'] = np.where(df[[1, 2]].isnull().all(axis=1), 'abc', 'cuz')
    
    In [280]: df
    Out[280]:
         0    1    2  new
    0  1.0  2.0  3.0  cuz
    1  4.0  NaN  NaN  abc
    2  NaN  NaN  9.0  cuz
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多