gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 00:18:30 25 4
gpt4 key购买 nike

我得到了一个如下所示的 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,因为如果选择一行它会返回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

还可以使用 read_csv 中的 parse_datesindex_col 参数将列转换为日期时间对于DatetimeIndex:

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

关于python - 从数据框中获取索引作为日期时间对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59123673/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com