如何通过行索引从Pandas DataFrame中获取日期时间
按行索引获取DataFrame的日期值
你需要实现一个类似get_datetime(dataframe, row_index=1)的函数,从指定行索引位置返回2022-01-11格式的日期,对应的DataFrame如下:
open high low close volume dividends stock splits Date 2022-01-06 21.99 22.22 21.59 22.18 1956300 0 0 2022-01-11 22.32 22.93 22.23 22.92 1885700 0 0 2022-01-21 22.40 22.55 22.02 22.13 2265500 0 0 2022-01-26 22.28 22.72 21.79 22.05 2247600 0 0 2022-01-31 22.02 22.92 21.72 22.86 2955500 0 0 2022-02-10 24.73 25.51 24.59 25.29 4069300 0 0 2022-02-15 24.85 25.57 24.56 25.47 5661100 0 0 2022-02-25 24.59 25.07 24.46 24.67 3722400 0 0 2022-03-02 23.20 23.95 23.15 23.82 3268100 0 0 2022-03-07 21.54 21.60 19.51 19.59 10102600 0 0
解决方案
你的DataFrame把日期设为了行索引(DatetimeIndex类型),直接提取对应位置的索引值再格式化即可,函数实现如下:
def get_datetime(dataframe, row_index=1): # 获取指定行索引位置的datetime对象 date_item = dataframe.index[row_index] # 格式化为YYYY-MM-DD格式的字符串返回 return date_item.strftime('%Y-%m-%d')
使用示例
调用函数传入你的DataFrame:
# 假设你的DataFrame变量名为df result = get_datetime(df, row_index=1) print(result) # 输出:2022-01-11
如果不需要字符串格式,想要保留datetime对象,直接返回date_item即可。
内容的提问来源于stack exchange,提问作者Sedmaister
相关产品推荐
相关产品推荐

