报错“String object has no attribute 'str'”,求Python代码修复方案
错误原因与修复方案
错误原因
你代码里的x是普通Python字符串,而.str属性是Pandas Series/DataFrame对象才有的专属方法,普通字符串没有这个属性,所以触发了报错。
修复方法
情况1:仅处理单个普通字符串
直接用Python原生的in关键字判断是否包含目标词,搭配np.where使用:
import numpy as np x = 'this string is supposed to contain windows' result = np.where('windows' in x, 'Windows', 'Non Windows')
情况2:原本要处理Pandas序列(批量字符串场景)
如果你的需求是批量处理字符串,需要先把x转为Pandas Series对象,再使用.str.contains()方法:
import pandas as pd import numpy as np x = pd.Series(['this string is supposed to contain windows']) result = np.where(x.str.contains('windows'), 'Windows', 'Non Windows')
内容的提问来源于stack exchange,提问作者M4RCUS.ERYX
相关产品推荐
相关产品推荐

