I'd like to create a new column in a Pandas data frame based on a substring search of one column and an inverse of another column. Here is some data:
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
I would like to be able to create a new column named Country based on the following logic:
a) if the Manufacturer column contains the substring 'ABC' and the Color column contains the substring 'Red', then write 'United States' to the Country column
b) if the Manufacturer column contains the substring 'DEF', then write 'Canada to the Country column
c) if the Manufacturer column contains the substring 'ABC' and the Color column does NOT contain the substring 'Red', then write 'England' to the Country column.
My attempt is as follows:
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')))
But, this gets the following error:
TypeError: Cannot perform 'rand_' with a dtyped [float64] array and scalar of type [bool]
The error message suggests that it might be a matter of operator precedence, as mentioned in:
Python error: TypeError: cannot compare a dtyped [float64] array with a scalar of type [bool]
I believe I'm using parentheses properly here (although maybe I'm not).
Does anyone see the cause of this error? (or know of a more elegant want to accomplish this?)
Thanks in advance!