Answers for "replace method pandas"

6

find and replace string dataframe

df['range'] = df['range'].str.replace(',','-')
Posted by: Guest on March-29-2021
1

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

# Basic syntax:
df.loc[~df['col_name'].isin(list_of_allowed_vals), "col_name"] = "None"

# Example usage:
# Build example dataframe:
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'] # Define list of elements to keep

# Replace values that aren't the list of allowed values with "None":
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

# If you want to do this on all columns of the dataframe, run:
dataframe[~dataframe.isin(list_of_allowed_vals)] = "None"
Posted by: Guest on November-12-2020
3

pandas dataframe replace inf

df.replace([np.inf, -np.inf], np.nan)
Posted by: Guest on June-02-2020

Python Answers by Framework

Browse Popular Code Answers by Language