【发布时间】:2021-03-01 04:56:58
【问题描述】:
我想根据一列的子字符串搜索和另一列的倒数在 Pandas 数据框中创建一个新列。这是一些数据:
import pandas as pd
import numpy as np
df = pd.DataFrame({'Manufacturer':['ABC-001', 'ABC-002', 'ABC-003', 'ABC-004', 'DEF-123', 'DEF-124', 'DEF-125', 'ABC-987', 'ABC-986', 'ABC-985'],
'Color':['04-Red', 'vs Red - 07', 'Red', 'Red--321', np.nan, np.nan, np.nan, 'Blue', 'Black', 'Orange'],
})
Manufacturer Color
0 ABC-001 04-Red
1 ABC-002 vs Red - 07
2 ABC-003 Red
3 ABC-004 Red--321
4 DEF-123 NaN
5 DEF-124 NaN
6 DEF-125 NaN
7 ABC-987 Blue
8 ABC-986 Black
9 ABC-985 Orange
我希望能够根据以下逻辑创建一个名为 Country 的新列:
a) 如果Manufacturer 列包含子字符串“ABC”且Color 列包含子字符串“Red”,则将“United States”写入Country 列
b) 如果Manufacturer 列包含子字符串'DEF',则将'Canada 写入Country 列
c) 如果Manufacturer 列包含子字符串“ABC”并且Color 列NOT 包含子字符串“Red”,则将“England”写入Country 列.
我的尝试如下:
df['Country'] = np.where((df['Manufacturer'].str.contains('ABC')) & (df['Color'].str.contains('Red', na=False)), 'United States', # the 'a' case
np.where(df['Manufacturer'].str.contains('DEF', na=False), 'Canada', # the 'b' case
np.where((df['Manufacturer'].str.contains('ABC')) & (df[~df['Color'].str.contains('Red', na=False)]), 'England', # the 'c' case
'ERROR')))
但是,这会得到以下错误:
TypeError: Cannot perform 'rand_' with a dtyped [float64] array and scalar of type [bool]
错误消息表明这可能是运算符优先级的问题,如下所述:
Python error: TypeError: cannot compare a dtyped [float64] array with a scalar of type [bool]
我相信我在这里正确地使用了括号(尽管我可能不是)。
有人看到这个错误的原因吗? (或者知道更优雅的想要实现这个?)
提前致谢!
【问题讨论】: