替换数据帧中不包含特定字符串的所有值

2024-09-26 18:11:43 发布

您现在位置: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

不知道我在这里错过了什么。感谢您的帮助


Tags: 数据代码namedfobject错误amountcountry
3条回答

数据可能包含缺少的国家,即NaN。在条件中使用== True而不是否定:

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

或者更简单,交换替换项:

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

这可能是由于Nan列中的Country导致的

请在^{}中传递na=False参数:

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

你的代码对我来说很好。可能您的完整数据集在某个地方有NaN's,或者它也不适用于您的示例数据集

您也可以尝试不使用Numpy:

df.loc[~df['Country'].str.contains('land'), 'Country'] = "Others"

相关问题 更多 >

    热门问题