【问题标题】:How to use two condition in np.where如何在 np.where 中使用两个条件
【发布时间】:2018-03-21 16:16:02
【问题描述】:
data['BUILDING CLASS CATEGORY'] = np.where(data['BUILDING CLASS 
CATEGORY']!='01 ONE FAMILY DWELLINGS' or '02 TWO FAMILY 
DWELLINGS ', 'OTHERS' , data['BUILDING CLASS CATEGORY'])

都没有

data['BUILDING CLASS CATEGORY'] = np.where(data['BUILDING CLASS 
CATEGORY']!='01 ONE FAMILY DWELLINGS' or data['BUILDING 
CLASS CATEGORY']!='02 TWO FAMILY DWELLINGS', 'OTHERS' , 
data['BUILDING CLASS CATEGORY'])

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

【问题讨论】:

  • and 使用 &,or 使用 ^
  • 并将比较包装在 () 中,以便他们首先评估,例如(a<0) | (b>3).
  • 友好建议:格式化会使这个问题更具可读性。例如,其中包含大写字母和空格的长字符串使其非常难以阅读,并使事情转到下一行。这真的很粗糙。可读性对问题很重要!此外,所有大写字母本质上都很烦人。 :)

标签: python numpy


【解决方案1】:

您的第二次尝试非常接近,使用 numpy.where 并注意 [its] 条件语句使用 bitwise operators (& | ^ << >> ~)。
将所有内容放在一起,我们将拥有以下内容;

import pandas as pd
import numpy as np

data = pd.DataFrame({'COL': ['01 thing','02 thing','03 thing']})

print(data)
>>>    COL
>>> 0  01 thing
>>> 1  02 thing
>>> 2  03 thing

data['COL'] = np.where((data['COL'] != '01 thing') | 
                       (data['COL'] != '02 thing'), 'other', data['COL'])

print(data)
>>>    COL
>>> 0  other
>>> 1  other
>>> 2  other

建议:)如果您想替换所有不是'01 thing''02 thing' 的记录,您可能想用& 替换|。另外,我会考虑使用str.startswith
将其替换为您的np.where(condition) 我们有;

data['COL'] = np.where(~data['COL'].str.startswith('01') &
                       ~data['COL'].str.startswith('02'), 'other', data['COL'])

print(data)
>>>    COL
>>> 0  01 thing
>>> 1  other
>>> 2  02 thing

【讨论】:

    【解决方案2】:

    要让np.where() 处理多个条件,请执行以下操作:

    np.where((condition 1) & (condition 2)) # for and
    np.where((condition 1) | (condition 2)) # for or
    

    为什么我们必须这样处理(用括号和& 而不是and)?坦率地说,我不是 100% 确定,但请参阅关于这个问题的很长的讨论 at this post

    【讨论】:

      猜你喜欢
      • 2021-09-17
      • 2021-09-01
      • 2022-06-13
      • 2019-10-03
      • 2020-04-02
      • 1970-01-01
      • 2020-06-16
      • 1970-01-01
      • 2021-12-18
      相关资源
      最近更新 更多