如何更改列中的同一字符串并使用Pandas将其永久化

2024-05-15 18:05:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图将竞赛栏下的字符串“SLL”更改为“League”,但当我尝试此操作时:

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


Tags: 字符串httpscomviewtruegoogledrivedataset
2条回答

基于此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)

假设您有一个如下所示的数据帧:

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

希望它能澄清

相关问题 更多 >