【问题标题】:How do I change column values in pandas if it contains a part of string which I want to replace?如果 pandas 包含我要替换的字符串的一部分,我该如何更改它的列值?
【发布时间】:2020-09-29 04:13:18
【问题描述】:

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

在名为“您最信任哪个来源以获取有关政治的见解?”的列下所有包含字符串/子字符串“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()。

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

【问题讨论】:

    标签: pandas dataframe data-cleaning


    【解决方案1】:

    诀窍是使用.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"
    

    【讨论】:

      【解决方案2】:
      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'
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-09-19
        • 2017-11-19
        • 2018-10-12
        • 2019-03-15
        • 1970-01-01
        • 2022-11-25
        • 2012-04-27
        相关资源
        最近更新 更多