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
Replace values in a series pandas
提问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.replace
is different to pd.Series.str.replace
:
pd.Series.replace
不同于pd.Series.str.replace
:
pd.Series.replace
is used to replace an element in its entirety. It will work also on non-string elements.pd.Series.str.replace
is used to replace substrings, optionally using regex.
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.replace
by 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 regex
flag is set to true.
str.replace
默认情况下,基于正则表达式的替换也适用于部分匹配。replace
, OTOH,默认情况下只会根据完全匹配执行替换,除非该regex
标志设置为 true。
data['Organization'] = (
data['Organization'].replace({'Greece': 'Rome'}, regex=True))