【问题标题】:How do I change the same string within a column and make it permanent using Pandas如何更改列中的相同字符串并使用 Pandas 使其永久化
【发布时间】:2023-03-12 13:27:01
【问题描述】:

我正在尝试将比赛列下的字符串“SLL”更改为“联赛”,但是当我尝试这样做时:

messi_dataset.replace("SLL", "League",regex = True)

它只是将第一个“SLL”更改为“League”,但随后其他“SLL”字符串变为“UCL。我不知道为什么。我还尝试将 regex = True 更改为 inlace = True 但没有运气。

https://drive.google.com/file/d/1ldq6o70j-FsjX832GbYq24jzeR0IwlEs/view?usp=sharing

https://drive.google.com/file/d/1OeCSutkfdHdroCmTEG9KqnYypso3bwDm/view?usp=sharing

【问题讨论】:

  • 我们可以看看你的代码吗?
  • 把相关代码放在这里,不要链接到Google Drive。
  • 是的,我使用的代码是:messi_dataset.replace("SLL", "League",regex = True) 应该包含哪些其他相关代码?
  • messi_dataset 它是带有列的主要数据集,或者它只是一个熊猫系列
  • @GeorgeZambrano 你应该附上一个最小的、可重现的例子。请参阅本指南了解更多信息:stackoverflow.com/help/minimal-reproducible-example

标签: python pandas jupyter-notebook


【解决方案1】:

基于此Answer 测试此代码:

messi_dataset['competitions'] = messi_dataset['competitions'].replace("SLL", "League")

另外,有很多不同的方法可以做到这一点,比如我测试过的这个:

messi_dataset.replace({'competitions': 'SLL'}, "League")

对于那些“SLL”是另一个词的一部分的情况:

messi_dataset.replace({'competitions': 'SLL'}, "League", regex=True)

【讨论】:

  • 完美!
【解决方案2】:

假设你有一个如下的数据框:

import pandas as pd
import re
df = pd.DataFrame({'Competitions': ['SLL', 'sll','apple', 'banana', 'aabbSLL', 'ccddSLL']})

# write a regex pattern that replaces 'SLL' 
# I assumed case-irrelevant

regex_pat = re.compile(r'SLL', flags=re.IGNORECASE)
df['Competitions'].str.replace(regex_pat, 'league', regex=True)

#   Input DataFrame
    Competitions
0   SLL
1   sll
2   apple
3   banana
4   aabbSLL
5   ccddSLL

Output:

0        league
1        league
2         apple
3        banana
4    aabbleague
5    ccddleague
Name: Competitions, dtype: object

希望它澄清。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-28
    • 1970-01-01
    • 1970-01-01
    • 2010-12-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-07
    • 2016-09-19
    相关资源
    最近更新 更多