检查字符串组的列,如果存在则替换为 1 如果不存在则替换为 0 - python、pandas、逻辑运算符

Check columns for groups of strings, replace with 1 if they exist 0 if they do not - python, pandas, logical operators

我正在尝试在 pandas 数据帧的列中搜索一组字符串,如果字符串存在则替换为 1,如果不存在则替换为 0。

根据下面的示例,这在第一次通过时工作正常:

df = pd.DataFrame({'ID':[1,2,3,4], 'Event':['1 Day', '2 Days','3 Days','4 Days']})
df['Event'] = np.where(df['Event'].str.contains('3 Days|4 Days'),1,df['Event'])

df

但是当我尝试应用相反的逻辑并替换字符串不存在的实例时:

df = pd.DataFrame({'ID':[1,2,3,4], 'Event':['1 Day', '2 Days','3 Days','4 Days']})
df['Event'] = np.where(df['Event'].str.contains('3 Days|4 Days'),1,df['Event'])
df['Event'] = np.where(~df['Event'].str.contains('3 Days|4 Days'),0,df['Event'])  

df

我收到这个错误 - TypeError: bad operand type for unary ~: 'float'

我尝试使用逻辑运算符以便同时发生这些操作:

df = pd.DataFrame({'ID':[1,2,3,4], 'Event':['1 Day', '2 Days','3 Days','4 Days']})
df['Event'] = np.where(df['Event'].str.contains('3 Days|4 Days'),1,df['Event']) & np.where(~df['Event'].str.contains('3 Days|4 Days'),0,df['Event'])  

df

但收到此错误...TypeError: unsupported operand type(s) for &: 'str' and 'int'

我最终想要实现的是一个 df,它用 1 替换所有存在字符串的单元格,用 0 替换那些字符串不存在的实例,这样我就可以分析了。像这样:

ID  Event
1   0  
2   0
3   1
4   1

这一行之后:

df['Event'] = np.where(df['Event'].str.contains('3 Days|4 Days'),1, df['Event'])

df['Event'] 包含 1 不是字符串,所以第二次检查(在 np.where 内):

df['Event'].str.contains('3 Days|4 Days')

它returns:

0    False
1    False
2      NaN
3      NaN
Name: Event, dtype: object

因为 NaN 不计算 ~NaN,它 returns 一个错误。

要获得期望的结果,只需使用 np.where 一次 select 如果为真则为 1,否则为 0:

df['Event'] = np.where(df['Event'].str.contains('3 Days|4 Days'), 1, 0)

输出:

   ID  Event
0   1      0
1   2      0
2   3      1
3   4      1

由于 True/False1/0 相同,您可以简单地使用条件语句作为 df['Event'] 的新数据.在这种情况下,np.where(或 df.loc)是不必要的额外步骤。

df['Event'] = df['Event'].str.contains('3 Days|4 Days').astype(int)

   ID  Event
0   1      0
1   2      0
2   3      1
3   4      1