Pandas:如果预定义列表中不存在列值,则将列值替换为空 [英] Pandas: Replace column values to empty if not present in pre-defined list

查看:72
本文介绍了Pandas:如果预定义列表中不存在列值,则将列值替换为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个列表,X,其中包含一组列的合法值.比如说,我有 A 列.我想替换(设置​​为空字符串)df['A'] 中的元素,如果它们的值不在 X 中.我怎样才能在 Pandas 中有效地做到这一点?

I have a list, X, that contains a set of legal values for a column. Say, I have column A. I want to replace (set to empty string) elements in df['A'] if their value is not in X. How can I do that efficiently in Pandas?

我知道有 isin(),但这只是检查值是否存在并返回一系列真/假.

I know there is isin(), but that just checks if the values are present and returns a Series of True/False.

推荐答案

试试这个:

df.loc[~df.A.isin(X), 'A'] = ''

这篇关于Pandas:如果预定义列表中不存在列值,则将列值替换为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆