如果 pandas 中包含我要替换的字符串的一部分,我该如何更改它的列值?

How do I change column values in pandas if it contains a part of string which I want to replace?

我正在清理调查中的表格结果。

在名为 'Which source do you trust the most to get insights on politics?' 的列下,所有包含 string/substring 'news' 行条目的条目都应替换为字符串 'newspapers or news apps'

这里,'responses'是调查回复的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()。

请帮忙!任何潜在客户表示赞赏:)

诀窍是使用 .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"
Colname = 'Which source do you trust the most to get insights on politics?' 
responses.loc[responses[Colname].str.contains('news'), Colname]= 'newspapers or news apps'