python - 替换熊猫数据框中不包含特定字符串的所有值
问题描述
我有以下数据框:
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
在您的Country
专栏中发生的。
请传入na=False
参数Series.str.contains
:
df['Country'] = np.where(~df['Country'].str.contains("land", na=False), "Others", df['Country'])
推荐阅读
- nginx - 在端口 80 和 443 上没有连接到 Nginx docker 容器
- javascript - 为什么我的函数不断添加 DOM 节点?
- url-rewriting - IIS 重写全局规则仅适用于默认文档
- javascript - Angular 材质 sidenav 项目在单击后保持焦点
- sql - Postgres Query 根据两个不同的行选择值
- java - FileNotFoundException - 拒绝访问
- python-3.x - Py2app 找不到模块
- sql - 具有多个属性且数据库表不多的产品数据库
- c++ - 用唯一的 int 填充数组
- python - 对字典中的字典列表进行排序