Use regex (seperate the strings by |):
df['schoolname'] = df['schoolname'].str.replace('high|school', "")
Answer from Andy Hayden on Stack OverflowI have a dataframe:
{'country': {0: 'Afghanistan?*', 1: 'Albania?*'},
'region': {0: 'Asia', 1: 'Europe'},
'subregion': {0: 'Southern Asia', 1: 'Southern Europe'},
'rate_per_1000': {0: 6.7, 1: 2.1},
'count': {0: '2,474', 1: '61'},
'year': {0: 2018, 1: 2020},
'source': {0: 'NSO', 1: 'NSO'}}
country region subregion rate_per_1000 count year source
0 Afghanistan?* Asia Southern Asia 6.7 2,474 2018 NSO
1 Albania?* Europe Southern Europe 2.1 61 2020 NSOThere are multiple bad characters here that I want to get rid of. I made a short function for .apply() to get rid of them, however I am looping over a defined list of bad characters. This gives a bad code smell to me, I think this operation could be more vectorized in some way. This is what I've tried:
bad_chars = ['?', '*', ',']
def string_cleaner(col):
if col.dtype == 'object':
for char in bad_chars:
col = col.str.replace(f'{char}', '')
return col
homicide_by_country = homicide_by_country.apply(string_cleaner)
homicide_by_country
country region subregion rate_per_1000 count year source
0 Afghanistan Asia Southern Asia None 2474 None NSO
1 Albania Europe Southern Europe None 61 None NSOMy desired outcome is a more pythonic/pandonic technique for accomplishing the same outcome.
You may notice for some reason my rate_per_1000 columns goes blank. I haven't troubleshot that problem yet but if you spot something obvious I'm all ears.
python - pandas replace (erase) different characters from strings - Stack Overflow
python - How to replace multiple character in string of data frame in pandas? - Stack Overflow
python - Replace multiple characters across all columns pandas df - Stack Overflow
python - pandas string replace multiple character in a cell - Stack Overflow
Use regex (seperate the strings by |):
df['schoolname'] = df['schoolname'].str.replace('high|school', "")
You can create a dictionary and then .replace({}, regex=True) method:
replacements = {
'schoolname': {
r'(high|school)': ''}
}
df.replace(replacements, regex=True, inplace=True)
I'm trying to remove the special characters '$' and ','. Can the code below be shortened so I can perform the operation just once?
df['ListPricePerUnit'] = df['ListPricePerUnit'].str.replace('$','').str.replace(',','')
df['PurchasePricePerUnit'] = df['PurchasePricePerUnit'].str.replace('$','').str.replace(',','')