我有以下数据框:
df
Name Country Amount_1 Amount_2
Neo Monaco 100.2 100.2
Nord Myland 100.2 100.2
Nemo Marek 100.2 100.2
Novak Mozart 100.2 100.2
我想替换Country列中不包含字符串“land”的所有条目
我使用以下代码进行相同操作:
df['Country'] = np.where(~df['Country'].str.contains("land"), "Others", df['Country'])
但我得到了以下错误:
TypeError: bad operand type for unary ~: 'float'
如果从上述代码中删除.str,则会出现以下错误:
AttributeError: 'Series' object has no attribute 'contains'
以下是df的数据类型:
Name object
Country object
Amount_1 float64
Amount_2 float64
dtype: object
不知道我在这里错过了什么。感谢您的帮助
数据可能包含缺少的国家,即
NaN
。在条件中使用== True
而不是否定:或者更简单,交换替换项:
这可能是由于
Nan
列中的Country
导致的请在^{} 中传递
na=False
参数:你的代码对我来说很好。可能您的完整数据集在某个地方有
NaN's
,或者它也不适用于您的示例数据集您也可以尝试不使用Numpy:
相关问题 更多 >
编程相关推荐