在字符串中查找子字符串

时间:2019-03-11 12:09:10

标签: python pandas

我有一个带有“状态”列的数据框 如果状态值包含单词“ Won”,我将状态栏的值替换为1,否则将其替换为0

我这样尝试:

s = oppty_oppline['status']
if s.find("Won") == -1:
       oppty_oppline['status']=0
else:
        oppty_oppline['status']=1

但是我遇到了这个错误:

AttributeError                            Traceback (most recent call last)
<ipython-input-23-7d82ff1c0e85> in <module>()
      1 s = oppty_oppline['status']
----> 2 if s.contains("Won") == -1:
      3        oppty_oppline['status']=0
      4 else:
      5         oppty_oppline['status']=1

~/anaconda3/envs/python3/lib/python3.6/site-packages/pandas/core/generic.py in __getattr__(self, name)
   3612             if name in self._info_axis:
   3613                 return self[name]
-> 3614             return object.__getattribute__(self, name)
   3615 
   3616     def __setattr__(self, name, value):

AttributeError: 'Series' object has no attribute 'contains'

任何想法请帮助我解决此问题

感谢

1 个答案:

答案 0 :(得分:2)

Series.str.contains用于布尔掩码,并通过强制转换为整数将True/False映射到1/0

oppty_oppline['status'] = oppty_oppline['status'].str.contains('Won').astype(int)

或使用numpy.where

oppty_oppline['status'] = np.where(oppty_oppline['status'].str.contains('Won'), 0, 1)