简体   繁体   中英

Pandas: Replace column values to empty if not present in pre-defined list

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?

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'] = ''

You can do it with apply:

import pandas as pd

x = ['a', 'b', 'c']
data = {'foo':['a', 'a', 'q', 'p']}
df = pd.DataFrame.from_dict(data)

df_new = df['foo'].apply(lambda i: i if i in x else '')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM