replace method pandas code example
Example 1: find and replace string dataframe
df['range'] = df['range'].str.replace(',','-')
Example 2: pandas dataframe replace inf
df.replace([np.inf, -np.inf], np.nan)
Example 3: python replace pandas df elements if they aren't in a list
df.loc[~df['col_name'].isin(list_of_allowed_vals), "col_name"] = "None"
dataframe = pd.DataFrame(['ok','keep','wtf','ok'], columns=['col_name'])
print(dataframe)
col_name
0 ok
1 keep
2 wtf
3 ok
list_of_allowed_vals = ['ok', 'keep']
dataframe.loc[~dataframe['col_name'].isin(list_of_allowed_vals), "col_name"] = "None"
print(dataframe)
col_name
0 ok
1 keep
2 None
3 ok
dataframe[~dataframe.isin(list_of_allowed_vals)] = "None"