繁体   English   中英

从数据框中获取索引作为日期时间对象

[英]Get index as datetime object from dataframe

我有一个看起来像这样的 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

我将 csv 读取为 pandas 数据框并将有效列设置为索引。 我也将它转换为 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

现在我想获取索引作为某一行的日期时间对象。 我怎么做?

我试过了,但没用

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'

您忘记分配回去,因为to_datetime不是inplace函数,然后测试Series.name ,因为如果选择一行,它会按DataFrame的索引返回带有名称的Series

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

此外,对于将列转换为日期时间,可以在read_csv中为DatetimeIndex使用parse_datesindex_col参数:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM