【问题标题】:python pandas column conditional on two other column valuespython pandas列以其他两个列值为条件
【发布时间】:2017-08-20 16:19:18
【问题描述】:

如果一列或另一列有值,python pandas 有没有办法应用条件?

对于一列,我知道如果列标题包含单词“test”,我可以使用以下代码来应用测试标志。

df['Test_Flag'] = np.where(df['Title'].str.contains("test|Test"), 'Y', '')

但是如果我想说列标题或列副标题是否包含“测试”一词,请添加测试标志,我该怎么做呢?

这显然行不通

df['Test_Flag'] = np.where(df['Title'|'Subtitle'].str.contains("test|Test"), 'Y', '')

【问题讨论】:

    标签: python pandas numpy dataframe conditional


    【解决方案1】:

    使用@jezrael 的设置

    df = pd.DataFrame(
        {'Title':['test','Test','e', 'a'],
         'Subtitle':['b','a','Test', 'a']})
    

    pandas

    你可以stack + str.contains + unstack

    import re
    
    df.stack().str.contains('test', flags=re.IGNORECASE).unstack()
    
      Subtitle  Title
    0    False   True
    1    False   True
    2     True  False
    3    False  False
    

    把所有东西都放在一起

    truth_map = {True: 'Y', False: ''}
    truth_flag = df.stack().str.contains(
        'test', flags=re.IGNORECASE).unstack().any(1).map(truth_map)
    df.assign(Test_flag=truth_flag)
    
      Subtitle Title Test_flag
    0        b  test         Y
    1        a  Test         Y
    2     Test     e         Y
    3        a     a        
    

    numpy

    如果性能是一个问题

    v = df.values.astype(str)
    low = np.core.defchararray.lower(v)
    flg = np.core.defchararray.find(low, 'test') >= 0
    ys = np.where(flg.any(1), 'Y', '')
    df.assign(Test_flag=ys)
    
      Subtitle Title Test_flag
    0        b  test         Y
    1        a  Test         Y
    2     Test     e         Y
    3        a     a          
    

    幼稚时间测试

    【讨论】:

    • @jeangelj, flagre (RegEx) 模块中许多函数的“标准”参数。所以 pandas 将此标志进一步传递给 re.* 函数调用...
    • @jeangelj 我已经为您更新了另一个解决方案。
    【解决方案2】:

    如果有很多列,那么更简单的是创建子集 df[['Title', 'Subtitle']]apply contains,因为仅适用于 Series 并且每行至少检查一个 True any

    mask = df[['Title', 'Subtitle']].apply(lambda x: x.str.contains("test|Test")).any(axis=1)
    df['Test_Flag'] = np.where(mask,'Y', '')
    

    示例:

    df = pd.DataFrame({'Title':['test','Test','e', 'a'], 'Subtitle':['b','a','Test', 'a']})
    mask = df[['Title', 'Subtitle']].apply(lambda x: x.str.contains("test|Test")).any(axis=1)
    df['Test_Flag'] = np.where(mask,'Y', '')
    print (df)
      Subtitle Title Test_Flag
    0        b  test         Y
    1        a  Test         Y
    2     Test     e         Y
    3        a     a          
    

    【讨论】:

      【解决方案3】:
      pattern = "test|Test"
      match = df['Title'].str.contains(pattern) | df['Subtitle'].str.contains(pattern)
      df['Test_Flag'] = np.where(match, 'Y', '')
      

      【讨论】:

        猜你喜欢
        • 2018-07-09
        • 1970-01-01
        • 2012-08-24
        • 1970-01-01
        • 2019-09-04
        • 2020-06-02
        • 2013-01-19
        • 1970-01-01
        • 2018-09-26
        相关资源
        最近更新 更多