【问题标题】:Matching conditions in columns列中的匹配条件
【发布时间】:2022-01-12 12:52:08
【问题描述】:

我正在尝试匹配条件,以便如果 A 列和 B 列中都存在文本并且 C 列中存在 0,则代码应在 C 列中返回“新”(覆盖 0)。下面的示例数据框:

import pandas as pd
df = pd.DataFrame({"A":['something',None,'filled',None], "B":['test','test','test',None], "C":['rt','0','0','0']})

我已经尝试了以下方法,但是它似乎只接受最后一个条件,以便 C 列中的任何“0”条目都变为“新”,而不管 A 或 B 列中的 None。(在此示例中,我只期望“新” ' 出现在第 2 行。

import numpy as np

conditions = [(df['A'] is not None) & (df['B'] is not None) & (df['C'] == '0')]

values = ['new']

df['C'] = np.select(conditions, values, default=df["C"])

感谢任何帮助!

【问题讨论】:

    标签: pandas dataframe numpy conditional-statements


    【解决方案1】:

    使用

    mask = df[['A', 'B']].notna().all(1) & df['C'].eq('0')
    df.loc[mask, 'C'] = 'new'
    

    【讨论】:

      【解决方案2】:

      您需要使用.isna() 并在不是nan/none 的地方进行过滤(使用~),如下所示:

      conditions = [~(df['A'].isna()) & ~(df['B'].isna()) & (df['C'] == '0')]
      

      输出:

                 A     B    C
      0  something  test   rt
      1       None  test    0
      2     filled  test  new
      3       None  None    0
      

      【讨论】:

        【解决方案3】:

        使用Series.notna 进行测试None 或NaNs:

        conditions = [df['A'].notna() & df['B'].notna() & (df['C'] == '0')]
        

        或者:

        conditions = [df[['A','B']].notna().all(axis=1) & (df['C'] == '0')]
        

        values = ['new']
        
        df['C'] = np.select(conditions, values, default=df["C"])
        print (df)
                   A     B    C
        0  something  test   rt
        1       None  test    0
        2     filled  test  new
        3       None  None    0
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2018-10-01
          • 1970-01-01
          • 2022-11-24
          • 2018-08-30
          • 2014-10-03
          • 2020-05-28
          • 2019-11-14
          相关资源
          最近更新 更多