gpt4 book ai didi

python - Pandas 仅替换使用正则表达式

转载 作者:太空宇宙 更新时间:2023-11-03 14:57:14 28 4
gpt4 key购买 nike

我已经找到了解决方法,但我仍然对发生的事情感到好奇:

当我尝试像这样在 Pandas 中进行替换时:

merged4[['column1', 'column2', 'column3']] = merged4[['column1', 'column2', 'column3']].replace(to_replace='.', value=',')

它不工作。例如,我尝试了 Inplace 的所有不同变体。我还做了 astype(str) 因为列是 float64。

但是,当我这样做时:

merged4[['column1', 'column2', 'column3']] = merged4[['column1', 'column2', 'column3']].replace(to_replace='\.', value =',', regex=True)

它的作用就像魅力一样。

有什么问题吗?

最佳答案

当您不使用regex=True时,该方法将查找replace_to值的精确匹配。当您使用 regex=True 时,它​​也会查找子字符串。因此,当您使用该参数时,您的代码可以正常工作。示例

当您不使用regex=True参数时,replace方法将在系列中查找replace_to值的精确匹配。

df = pd.DataFrame()
df['k'] = ['YoYo.','mins.s.s','sos.s.','.','mama.mia']
df['k'].replace('.',',')
0       YoYo.1    mins.s.s2      sos.s.3           ,4    mama.mia

When you use regex = True it even matches the substrings of the series and changes the strings

df = pd.DataFrame()
df['k'] = ['YoYo.','mins.s.s','sos.s.','.','mama.mia']
df['k'].replace('\.',',',regex=True)
0       YoYo,1    mins,s,s2      sos,s,3           ,4    mama,mia

关于python - Pandas 仅替换使用正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45439506/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com