pandas 替换一系列熊猫中的值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/52104576/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 05:59:08  来源:igfitidea点击:

Replace values in a series pandas

pythonregexpandasreplaceseries

提问by grim_reaper

How come when i want to replace a value I have to use this block of code:

为什么当我想替换一个值时,我必须使用这段代码:

data['Organization'].str.replace('Greece','Rome')

why cant I use this:

为什么我不能使用这个:

data['Organization'].replace('Greece','Rome').

I've seen others use method two before without passing a string method. My question is can i pass a series method using replace function and what is the line of code?

我之前见过其他人使用方法二而没有传递字符串方法。我的问题是我可以使用替换函数传递一个系列方法吗?代码行是什么?

回答by jpp

pd.Series.replaceis different to pd.Series.str.replace:

pd.Series.replace不同于pd.Series.str.replace

Here's a minimal example demonstrating the difference:

这是一个演示差异的最小示例:

df = pd.DataFrame({'A': ['foo', 'fuz', np.nan]})

df['B'] = df['A'].replace(['foo', 'fuz'], ['food', 'fuzzy'])
df['C'] = df['A'].str.replace('f.', 'ba', regex=True)

print(df)

     A      B    C
0  foo   food  bao
1  fuz  fuzzy  baz
2  NaN    NaN  NaN

回答by cs95

str.replaceby default does a regex based replacement which also works with partial matches. replace, OTOH, will only perform replacements based on full matches by default unless the regexflag is set to true.

str.replace默认情况下,基于正则表达式的替换也适用于部分匹配。replace, OTOH,默认情况下只会根据完全匹配执行替换,除非该regex标志设置为 true。

data['Organization'] = (
    data['Organization'].replace({'Greece': 'Rome'}, regex=True))