Search code examples
pandasdataframe

How can I drop a row from a pandas.core.frame.DataFrame by index name?


I have a dataframe that looks like:

              GBPEUR
date                
2018-06-22  1.140732
2018-06-25  1.135847
2018-06-26  1.134301
1900-01-01       NaN

df.columns: Index(['GBPEUR'], dtype='object')

df.index: Index([2018-06-22, 2018-06-25, 2018-06-26, 1900-01-01], dtype='object', name='date')

I am trying to do:

df = df.drop(index='1900-01-01')

But I run into:

KeyError: "['1900-01-01'] not found in axis"

I am really confused, isn't 1900-01-01 in the axis?


Solution

  • If the index values are of type datetime.date, you can select them using pandas.Timestamp:

    import pandas as pd
    
    data = {
        "date": ["2018-06-22", "2018-06-25", "2018-06-26", "1900-01-01"],
        "GBPEUR": [1.140732, 1.135847, 1.134301, None],
    }
    
    df = pd.DataFrame(data)
    
    df["date"] = pd.to_datetime(df["date"]).dt.date
    df.set_index("date", inplace=True)
    
    df = df.drop(index=pd.Timestamp("1900-01-01"))
    
                  GBPEUR
    date                
    2018-06-22  1.140732
    2018-06-25  1.135847
    2018-06-26  1.134301