首页 > 解决方案 > 替换熊猫数据框中不包含特定字符串的所有值

问题描述

我有以下数据框:

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

不知道我在这里缺少什么。任何帮助表示赞赏。

标签: pythonpandasdataframe

解决方案


这可能是由于Nan在您的Country专栏中发生的。

请传入na=False参数Series.str.contains

df['Country'] = np.where(~df['Country'].str.contains("land", na=False), "Others", df['Country'])

推荐阅读