【问题标题】:Pandas If else emptyPandas If else 为空
【发布时间】:2019-03-22 21:12:48
【问题描述】:

在 Pandas 中寻找 if else 语句的解决方案。示例:

col1  col2
1     NAN
2     NAN
3     NAN
NaN   01-2019
2     NAN

我的新列需要是 col3;

  • 当 col1 = 1 或更高时,添加“text a”
  • 当 col1 = 空且 col2 = 一个值时,取 col2 的值
  • 其他;设置值“文本 b”

我现在只有;当 col1 大于 1 时,设置文本 a,否则设置文本 b。

df['col3'] = np.where(df['col1']>=1, 'text a', 'text b')

但缺少检查 col1 是否为空且 col2 是否有值的部分。将该值放入 col3 中。

我怎样才能做到这一点?

谢谢!

-- 编辑--

当 col1 = 0 且 col2 有值时,在答案下也被问到,将 col3 设置为 col2 的值。

也是这样:

col1  col2
0     01-2019

【问题讨论】:

    标签: python pandas csv if-statement


    【解决方案1】:

    numpy.selectSeries.isnaSeries.notna 的测试缺失值和未缺失值一起使用:

    print (df)
       col1     col2
    0   0.0      NaN <-added row for test all coditions failed
    1   1.0      NaN
    2   2.0      NaN
    3   3.0      NaN
    4   NaN  01-2019
    5   2.0      NaN
    
    m1 = df['col1'] > =1
    m2 = df['col1'].isna() & (df['col2'].notna())
    #oldier pandas versions
    #m2 = df['col1'].isnull() & (df['col2'].notnull())
    df['col3'] = np.select([m1, m2], ['text a', df['col2']], 'text b')
    print (df)
       col1     col2     col3
    0   0.0      NaN   text b
    1   1.0      NaN   text a
    2   2.0      NaN   text a
    3   3.0      NaN   text a
    4   NaN  01-2019  01-2019
    5   2.0      NaN   text a
    

    另一个双np.where的解决方案:

    df['col3'] = np.where(m1, 'text a',
                 np.where(m2, df['col2'], 'text b'))
    

    编辑:

    条件改变了:

    m2 = (df['col1'] == 0) & (df['col2'].notna())
    

    【讨论】:

    • 太棒了!谢谢。当 col1=0 并且 col2 具有值时,您是否可以更改答案以记住它会采用 col3 中的值?
    • @HRR1337 - 检查上次编辑。 m2 = (df['col1'] == 0) &amp; (df['col2'].notna())。如果我的回答有帮助,请不要忘记 accept 它 - 单击答案旁边的复选标记,将其从灰色切换为已填充。谢谢。
    • 您好。供应商已经修改了那里的数据,现在库存中也可能有负值。例如在 col1,-10。我们如何才能实现 -10 也获得 col2 日期的解决方案?
    【解决方案2】:

    除了@jexrael 真棒答案之外,另一种方法是使用apply

    In [27]: def condition(r):
        ...:     if r['col1'] >= 1: return "text a"
        ...:     if pd.isnull(r['col1']) and pd.notnull(r['col2']): return r['col2']
        ...:     return "text b"
        ...:
    
    In [28]: df['col3'] = df.apply(condition, axis=1)
    
    In [29]: df
    Out[29]:
       col1     col2     col3
    0   1.0      NaN   text a
    1   2.0      NaN   text a
    2   3.0      NaN   text a
    3   NaN  01-2019  01-2019
    4   2.0      NaN   text a
    

    【讨论】:

      猜你喜欢
      • 2021-05-19
      • 2019-12-28
      • 2021-10-01
      • 1970-01-01
      • 2019-04-09
      • 2019-07-01
      • 2022-01-24
      • 1970-01-01
      • 2021-08-30
      相关资源
      最近更新 更多