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()。
请您参考如下方法:
您的第二次尝试非常接近,使用 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
