如何替换不在列表中的 Pandas Dataframe 中的所有值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34866856/
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
How to replace all values in a Pandas Dataframe not in a list?
提问by banad
I have a list of values. How can I replace all values in a Dataframe column not in the given list of values?
我有一个值列表。如何替换不在给定值列表中的 Dataframe 列中的所有值?
For example,
例如,
>>> df = pd.DataFrame(['D','ND','D','garbage'], columns=['S'])
>>> df
S
0 D
1 ND
2 D
3 garbage
>>> allowed_vals = ['D','ND']
I want to replace all values in the column S of the dataframe which are not in the list allowed_vals with 'None'. How can I do that?
我想将数据框 S 列中所有不在列表 allowed_vals 中的值替换为“无”。我怎样才能做到这一点?
回答by DSM
You can use isin
to check membership in allowed_list
, ~
to negate that, and then .loc
to modify the series in place:
您可以使用isin
来检查 中的成员资格allowed_list
,~
否定它,然后.loc
就地修改系列:
>>> df.loc[~df["S"].isin(allowed_vals), "S"] = "None"
>>> df
S
0 D
1 ND
2 D
3 None
because
因为
>>> df["S"].isin(allowed_vals)
0 True
1 True
2 True
3 False
Name: S, dtype: bool
If you want to modify the entire frame (not just the column S), you can make a frame-sized mask:
如果要修改整个框架(不仅仅是S列),可以制作一个框架大小的遮罩:
>>> df
S T
0 D D
1 ND A
2 D ND
3 garbage A
>>> df[~df.isin(allowed_vals)] = "None"
>>> df
S T
0 D D
1 ND None
2 D ND
3 None None