2024-10-06 12:30:05 发布
网友
我有一个数据框,如下所示:
这个数据帧的索引为datetime格式,我只想提取其中的“HH:MM”部分
我试过pd.DatetimeIndex(dfl.iloc[looppar]).hour
pd.DatetimeIndex(dfl.iloc[looppar]).hour
它不会按预期返回值。 在上面的代码中,looppar表示行数,比如第一行我只想提取格式为“09:18”的时间
如果您想要索引列表中包含小时:分钟
df1.index.strftime("%H:%M").tolist()
如果你只想要一个
df1.index.strftime("%H:%M")[2]
import pandas as pd # create sample dataframe idx = pd.date_range('2021-07-24 09:28:01', periods=3, freq='H') df = pd.DataFrame({ 'idx': idx, 'val': np.random.randn(len(idx)) }) df.set_index(pd.DatetimeIndex(df['idx']), inplace=True, drop=True) # apply function to index column to create new column with H:M df['hm'] = df.index.map(lambda i: i.strftime('%H:%M')) print(df)
输出:
val hm idx 2015-02-24 09:28:01 2015-02-24 09:28:01 -0.344819 09:28 2015-02-24 10:28:01 2015-02-24 10:28:01 -1.616330 10:28 2015-02-24 11:28:01 2015-02-24 11:28:01 1.711378 11:28
如果您想要索引列表中包含小时:分钟
如果你只想要一个
输出:
相关问题 更多 >
编程相关推荐