简体   繁体   中英

In Python, can the "replace function" replace strings equal to instead containting in a dataframe?

I have a dataframe that I scraped from Yahoo Finance. I want to replace missing values (which are noted as "-") so that I can adjusted the dataframe to numeric. However, when I use the replace function, it removes the "-" from negative numbers a well. Is there a way so that I can replace only strings in my dataframe exactly equal to "-"?

df[col] = df[col].apply(lambda x: x.replace('-', 'what you want') if x == '-' else x)

You can use the replace option on either the whole dataframe or a specific column:

#How to replace on a specific column
d = {'col1': [-10.5, 10.5, '-'], 'col2': [3, 4, '-']}
df = pd.DataFrame(d)
df['col1'].replace('-', 'something else')

#How to replace for entire dataframe
d = {'col1': [-10.5, 10.5, '-'], 'col2': [3, 4, '-']}
df = pd.DataFrame(d)
df.replace('-', 'something else')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM