pandas 取代价值观 [英] Pandas replace values
问题描述
我有以下数据框:
col
0 pre
1 post
2 a
3 b
4 post
5 pre
6 pre
我想将数据框中不包含"pre"的所有行替换为"nonpre",因此数据框看起来像:
I want to replace all rows in the dataframe which do not contain 'pre' to become 'nonpre', so dataframe looks like:
col
0 pre
1 nonpre
2 nonpre
3 nonpre
4 nonpre
5 pre
6 pre
我可以使用字典和熊猫替换来做到这一点,但是我只想选择不是'pre'的元素,然后将它们替换为'nonpre'.有没有一种更好的方法可以在不列出字典中所有可能的col值的情况下做到这一点?
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?
推荐答案
只要您对pandas允许的df.loc[condition, column]
语法感到满意,这很容易,只需执行df['col'] != 'pre'
即可找到所有应进行更改:
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['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
这篇关于 pandas 取代价值观的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!