Vader
Vader

Reputation: 6716

Get index as datetime object from dataframe

I got a csv file that looks like this

valid,temp,pressure
2019-11-25 12:00,22,4
2019-11-22 12:00,24,4
2019-11-20 12:00,24,5
2019-11-17 12:00,26,5

I read the csv as a pandas dataframe and set the valid column as the index. I also convert it to a pd.datetime

df = pd.read_csv(file)
pd.to_datetime(df['valid'])  # convert 'valid' column to pd.datetime objects
df = df.set_index('valid')  # set the 'valid' column as index

Now I want to get the index as a datetime object of a certain row. How do I do that?

I tried this but it doesn't work

row = df.iloc[2]
print(row.index.month)  # using .month just see if the returned object is a pd.datetime

AttributeError: 'Index' object has no attribute 'month'

Upvotes: 1

Views: 127

Answers (1)

jezrael
jezrael

Reputation: 862801

You forgot to assign back, because to_datetime is not inplace function and then test Series.name, because if select one row it return Series with name by index of row in DataFrame:

df = pd.read_csv(file)
df['valid'] = pd.to_datetime(df['valid'])
df = df.set_index('valid')
row = df.iloc[2]

print (row)
temp        24
pressure     5
Name: 2019-11-20 12:00:00, dtype: int64

print (row.name)
2019-11-20 12:00:00

print (row.name.month)
11

Also for convert column to datetimes is possible use parse_dates and index_col parameter in read_csv for DatetimeIndex:

df = pd.read_csv(file, parse_dates=['valid'], index_col=['valid'])
row = df.iloc[2]
print (row.name.month)
11

Upvotes: 2

Related Questions