【问题标题】:Python Dataframe: Create New Column Conditionally Using If Then Else Logic --> "The truth value of a Series is ambiguous"Python 数据框:有条件地使用 If Then Else 逻辑创建新列 --> “系列的真值不明确”
【发布时间】:2017-12-17 22:30:39
【问题描述】:

我正在使用以下代码创建一个新列,其值是基于我的 Python 数据框的其他两列中的值派生的。

# Create a list to store the data
MSP = []

for row in df_EVENT5_18['FLT']:
    if df_EVENT5_18['FLT'].str.contains('1234') & df_EVENT5_18['AR'].str.contains('ABC1'):
        MSP.append(29)
    elif (df_EVENT5_18['FLT'].str.contains('1234')) & (df_EVENT5_18['AR'].str.contains('ABC2')):
        MSP.append(25)
    else:
        MSP.append('')

# Create a new column from the list 
df_EVENT5_18['MSP'] = MSP

当我运行上面的代码时,我得到以下错误:

ValueError:Series 的真值不明确。使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()。

【问题讨论】:

    标签: python pandas if-statement conditional ambiguous


    【解决方案1】:

    每当您认为需要在 pandas 中使用循环时,请再次检查您的代码。一条线索是你有for row in df_EVENT5_18['FLT']:,但你从不使用row

    查找匹配字符串的索引

    在这种情况下,我们可以简单地使用布尔评估来获取我们想要设置的索引:

    has_flt_1234 = df_EVENT5_18['FLT'].str.contains('1234')
    want_29 = has_flt_1234 & df_EVENT5_18['AR'].str.contains('ABC1')
    want_25 = has_flt_1234 & df_EVENT5_18['AR'].str.contains('ABC2')
    

    使用布尔系列设置值

    然后根据需要设置适当的行:

    df_EVENT5_18['MSP'][want_25] = '25'
    df_EVENT5_18['MSP'][want_29] = '29'
    

    测试代码:

    import pandas as pd
    
    df_EVENT5_18 = pd.DataFrame(dict(
        FLT=['1234', '1234', '1235'],
        AR=['ABC1', 'ABC2', 'ABC1']
    ))
    
    print(df_EVENT5_18)
    
    has_flt_1234 = df_EVENT5_18['FLT'].str.contains('1234')
    want_29 = has_flt_1234 & df_EVENT5_18['AR'].str.contains('ABC1')
    want_25 = has_flt_1234 & df_EVENT5_18['AR'].str.contains('ABC2')
    
    # Create a new column from the list
    df_EVENT5_18['MSP'] = ''
    df_EVENT5_18['MSP'][want_25] = '25'
    df_EVENT5_18['MSP'][want_29] = '29'
    
    print(df_EVENT5_18)
    

    结果:

         AR   FLT
    0  ABC1  1234
    1  ABC2  1234
    2  ABC1  1235
    
         AR   FLT MSP
    0  ABC1  1234  29
    1  ABC2  1234  25
    2  ABC1  1235    
    

    【讨论】:

    • 感谢您的详细回复。你在这里应用逻辑的方式非常有趣......有没有办法用 if-elif-else 做到这一点?
    • 当然有。但不要那样做。这会更快。
    【解决方案2】:

    试试这样的:

    df[['new_col']] = df[['a','b'].apply(lambda (a,b) : pd.Series(your condition here),axis=1)
    

    【讨论】:

      猜你喜欢
      • 2020-10-16
      • 1970-01-01
      • 2021-01-28
      • 1970-01-01
      • 1970-01-01
      • 2017-05-05
      • 2014-03-09
      • 2021-12-28
      相关资源
      最近更新 更多