pandas - 如果 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()。
请帮忙!任何线索表示赞赏:)
解决方案
诀窍是创建一个布尔索引,.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"
推荐阅读
- java - 重复使用while循环的问题
- python - 将 pandas 数据帧的多列与具有不同长度和索引的另一个数据帧的一列进行比较
- eclipse - Eclipse 中没有“工具设置”
- xml - 如何根据 xml 中的可用字符串替换字符串
- android - 无法启动 Android Emulator 5.0
- javascript - 在子 ul 列表中显示父链接
- javascript - 如何从多个选择 HTML 中选择值
- python - “不可下标”问题 -python ode 解决
- javascript - 如何在 QUnit 测试中禁用“console.log”?
- html - 如何查找、导入和使用特定字体?