Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
548 views
in Technique[技术] by (71.8m points)

python - 从数据框中获取作为日期时间对象的索引(Get index as datetime object from dataframe)

I got a csv file that looks like this

(我有一个看起来像这样的csv文件)

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.

(我将csv读取为pandas数据框,并将有效列设置为索引。)

I also convert it to a pd.datetime

(我也将其转换为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'
  ask by Vader translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 :

(您忘记分配回去,因为to_datetime不是inplace函数,然后测试Series.name ,因为如果选择一行,则返回带有名称的Series (按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 :

(对于将列转换为日期时间,也可以在read_csvDatetimeIndex使用parse_datesindex_col参数:)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...