python replace pandas df elements if they aren 27t in a list

Solutions on MaxInterview for python replace pandas df elements if they aren 27t in a list by the best coders in the world

showing results for - "python replace pandas df elements if they aren 27t in a list"
Emilia
22 Jun 2016
1# Basic syntax:
2df.loc[~df['col_name'].isin(list_of_allowed_vals), "col_name"] = "None"
3
4# Example usage:
5# Build example dataframe:
6dataframe = pd.DataFrame(['ok','keep','wtf','ok'], columns=['col_name'])
7print(dataframe)
8  col_name
90       ok
101     keep
112      wtf
123       ok
13
14list_of_allowed_vals = ['ok', 'keep'] # Define list of elements to keep
15
16# Replace values that aren't the list of allowed values with "None":
17dataframe.loc[~dataframe['col_name'].isin(list_of_allowed_vals), "col_name"] = "None"
18print(dataframe)
19  col_name
200       ok
211     keep
222     None
233       ok
24
25# If you want to do this on all columns of the dataframe, run:
26dataframe[~dataframe.isin(list_of_allowed_vals)] = "None"