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. Ho
Solution 1:
try this:
df.loc[~df.A.isin(X), 'A'] = ''
Solution 2:
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'')
Post a Comment for "Pandas: Replace Column Values To Empty If Not Present In Pre-defined List"