Python 熊猫替换值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27117773/
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-08-19 01:26:46  来源:igfitidea点击:

Pandas replace values

pythonreplacepandas

提问by user308827

I have the following dataframe:

我有以下数据框:

     col
0    pre
1    post
2    a
3    b
4    post
5    pre
6    pre

I want to replace all rows in the dataframe which do not contain 'pre' to become 'nonpre', so dataframe looks like:

我想将数据框中不包含“pre”的所有行替换为“nonpre”,因此数据框如下所示:

     col
0    pre
1    nonpre
2    nonpre
3    nonpre
4    nonpre
5    pre
6    pre

I can do this using a dictionary and pandas replace, however I want to just select the elements which are not 'pre' and replace them with 'nonpre'. is there a better way to do that without listing all possible col values in a dictionary?

我可以使用字典和熊猫替换来做到这一点,但是我只想选择不是“pre”的元素并将它们替换为“nonpre”。有没有更好的方法来做到这一点而不在字典中列出所有可能的 col 值?

采纳答案by Marius

As long as you're comfortable with the df.loc[condition, column]syntax that pandas allows, this is very easy, just do df['col'] != 'pre'to find all rows that should be changed:

只要您对df.loc[condition, column]Pandas 允许的语法感到满意,这很容易,只需df['col'] != 'pre'查找所有应更改的行即可:

df['col2'] = df['col']
df.loc[df['col'] != 'pre', 'col2'] = 'nonpre'

df
Out[7]: 
    col    col2
0   pre     pre
1  post  nonpre
2     a  nonpre
3     b  nonpre
4  post  nonpre
5   pre     pre
6   pre     pre

回答by Mike

df[df['col'].apply(lambda x: 'pre' not in x)] = 'nonpre'