首页 > 解决方案 > 如果 pandas 包含我要替换的字符串的一部分,我该如何更改它的列值?

问题描述

我正在清理表格结果进行调查。

在名为“您最信任哪个来源以获得对政治的见解?”的栏目下 所有包含字符串/子字符串“新闻”的行条目的条目都应替换为字符串“报纸或新闻应用程序”

此处,“响应”是调查响应的 csv 文件的名称。

if responses['Which source do you trust the most to get insights on politics?'].str.contains('news') == True:
    responses['Which source do you trust the most to get insights on politics?'] = 'newspapers or news apps'

我收到以下代码错误:

ValueError:Series 的真值不明确。使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()。

请帮忙!任何线索表示赞赏:)

标签: pandasdataframedata-cleaning

解决方案


诀窍是创建一个布尔索引,.str.contains("news")然后使用它.loc来更新您的原始数据框并覆盖这些特定值。以下代码应该可以解决问题:

source_colname = 'Which source do you trust the most to get insights on politics?'
contains_news = responses[source_colname].str.contains('news')

responses.loc[contains_news, source_colname] = "newspapers or news app"

推荐阅读