【问题标题】:Why doesn't str.replace replace ALL values in selected pandas dataframe column?为什么 str.replace 不替换选定熊猫数据框列中的所有值?
【发布时间】:2022-01-12 20:51:39
【问题描述】:

我正在处理一个巨大的文件,该文件的列中包含我想要删除的无关值(如“|”键),但由于某种原因,我的 str.replace 函数似乎只适用于某些行在列中。

我在数据框summary 中的列看起来像这样:

Labels
test|test 1
test 2
test 3
test|test 4
test|test 5
test 6

如您所见,有些列已经是我想要的样子,只包含名称“test #”,但有些列有“test|”在前面,我想删除它。

我删除它们的功能是这样的:

correction = summary["Labels"].str.replace('test\|', '')

它似乎适用于大多数值,但是当我检查数据框中的管道(“|”)时(一旦我将 correctionsummary 合并),它说它找到了 9330 个:

found = summary[summary['Labels'].str.contains('|',regex=False)]
print(len(found))
print(found['Labels'].value_counts())

Results
9330
test|test-667     59
test|test-765     40
test|test-1810    39
test|test-685     36
test|test-1077    33
                  ..

有谁知道这是为什么,我该如何解决?

【问题讨论】:

  • 有没有可能是testtest||test-667
  • 在你写的函数中,correction 是一个series。但是当您查找错误时,correctiondataframe。所以你实际上并没有向我们展示你真正做了什么......
  • @Aryerez 啊,你说得对,对不起,忘记补充说我在删除不需要的值后将correction 放入summary 数据框中。我已经更正了上面的代码以反映这一点!
  • @Emily 您的问题可能来自于将correctionsummary 组合的方式错误,因为您没有向我们展示,我们无法知道。

标签: python pandas dataframe replace


【解决方案1】:

你在正确的轨道上。替换原始字符串如下

summary['Labels'] = summary['Labels'].str.replace(r'test\|','', regex=True)



Labels
0  test 1
1  test 2
2  test 4

【讨论】:

    【解决方案2】:

    试试str.extract:

    df['Labels'] = df['Labels'].str.extract(r'\|(.*)', expand=False) \
                               .combine_first(df['Labels'])
    print(df)
    
    # Output
       Labels
    0  test 1
    1  test 2
    2  test 3
    3  test 4
    4  test 5
    5  test 6
    

    【讨论】:

    • 感谢您的回复!我试过了,它似乎仍然不起作用,不知道为什么
    猜你喜欢
    • 1970-01-01
    • 2018-06-05
    • 2022-06-24
    • 2022-01-11
    • 1970-01-01
    • 1970-01-01
    • 2020-04-25
    • 2019-02-02
    相关资源
    最近更新 更多