1

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'

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

4 Comments

without assigning it back am I essentially not doing it in the first place?
@Vader - You do it, but no effect, because not inplace function.
I still get the same error after your suggested change.
df = df.set_index(pd.DatetimeIndex(df.valid)).drop("valid", axis=1)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.