【问题标题】:Python - Numpy Where Clause - The truth value of a Series is ambiguousPython - Numpy Where 子句 - 系列的真值不明确
【发布时间】:2020-12-24 17:02:49
【问题描述】:

我正在尝试根据其他列的条件创建一个新列。我有这个数据框:

number, flag_new, flag_math
1, TRUE, TRUE
2, FALSE, TRUE
3, TRUE, FALSE

如果 flag_new 为 True 且 flag_math 也为 TRUE,我希望在新列上有 1。如果 flag_new 为 FALSE 且 flag_math 为 TRUE,我想添加 0 否则为 -1。

预期结果是:

number, flag_new, flag_math, new_Column
    1, TRUE, TRUE, 1
    2, FALSE, TRUE, 0
    3, TRUE, FALSE, -1

为此,我有这个代码:

df['new_col'] = np.where(df['flag_new'] == 'TRUE' and df['flag_math'] == 'TRUE',1,
    np.where(df['flag_new'] == 'FALSE' and df['flag_math'] == 'TRUE',0, -1))

但我收到以下错误:

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

我做错了什么?

【问题讨论】:

  • pandasnumpy 使用按位运算符 (&,|,~) 代替 andornot 进行布尔运算
  • 你也可以使用np.where(df['flag_math'].eq('TRUE'), df['flag_new'].eq('TRUE').astype(int), -1)

标签: python pandas numpy


【解决方案1】:

and 和 or 用于标量运算。使用 numpy 函数,即 np.logical_and()np.logical_or() 进行向量比较,例如您的情况。例如:

df['new_col'] = np.where(np.logical_and(df['flag_new'] == 'TRUE', df['flag_math'] == 'TRUE'),1,
    np.where(np.logical_and(df['flag_new'] == 'FALSE', df['flag_math'] == 'TRUE'),0, -1))

老实说,尽管这种逻辑本身就是实现这一目标的复杂方法。您可以分两步简化此操作,并更有效地利用这些功能。

一个好方法可能是将列解析为布尔值本身(如果它们还没有)这将有助于未来基于布尔值的任何分析,if(value) 总是比value=='TRUE' 更可取。

def get_bool(key): #function derived from: https://stackoverflow.com/a/64380962/7212929 
    return {'True':True, 'False':False}.get(key) if  key.title() in {'True':True, 'False':False}.keys() else bool(key)

df[['flag_new', 'flag_math']] = df[['flag_new', 'flag_math']].applymap(get_bool) # convert boolean representations into actual bools

df['new_col'] = df.flag_math -1 +np.logical_and(df.flag_new, df.flag_math)  # add new column with simplified new logic

结果:

    number  flag_new    flag_math   new_col
0   1   True    True    1
1   2   False   True    0
2   3   True    False   -1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-22
    • 2018-01-11
    • 1970-01-01
    • 2011-06-11
    • 2019-10-09
    • 2014-05-03
    相关资源
    最近更新 更多