Home > Mobile >  Why does .set_index() used in single line return DatatimeIndex, but seperate lines returns RangeInde
Why does .set_index() used in single line return DatatimeIndex, but seperate lines returns RangeInde

Time:03-30

df = pd.read_sql_query(query, con, parse_dates=["time"]).set_index("time")
type(df_aq.index)

Why does this set index as DatetimeIndex (pandas.core.indexes.datetimes.DatetimeIndex) while the code below returns a RangeIndex (pandas.core.indexes.range.RangeIndex):

df = pd.read_sql_query(query, con, parse_dates=["time"])
df.set_index("time")
type(df_aq.index)

CodePudding user response:

In the first line you are setting the index while reading and saving it in the dataframe df, but in the code below where you get the RangeIndex, you are not saving the index but just temporarily assigning it.

That is why when you do type(df_aq.index) , you get to see the type of the original df and not the time column being assigned as index.

Either use:

df.set_index("time", inplace=True) 

or

df = df.set_index("time")

both should do the job.

CodePudding user response:

Change

df.set_index("time")

to

df.set_index("time", inplace=True)

By default inplace is set to false.

  • Related