The Python Oracle

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

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Quiet Intelligence

--

Chapters
00:00 Pandas: Replace Column Values To Empty If Not Present In Pre-Defined List
00:30 Accepted Answer Score 18
00:49 Answer 2 Score 4
00:59 Thank you

--

Full question
https://stackoverflow.com/questions/3800...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #pandas

#avk47



ACCEPTED ANSWER

Score 18


You can use the standard Pandas indexing here:

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

~df.A.isin(X) - will revert the boolean Series returned by df.A.isin(X) (i.e. False -> True and True -> False )




ANSWER 2

Score 4


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 '')