pythonreplacefinanceyahoo

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 "-"?


Solution

  • 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')