迭代日期时间索引中的日期列表 [英] Iterating over a list of dates from datetime index

查看:54
本文介绍了迭代日期时间索引中的日期列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的初始数据帧df:

                     discharge1  discharge2
datetime                                   
2018-04-25 18:37:00        5862        4427
2018-04-25 21:36:30        6421        4581
2018-04-25 22:13:00        5948        4779
2018-04-26 00:11:30        5703        4314
2018-04-26 02:27:00        4988        3868
2018-04-26 04:28:30        4812        3823
2018-04-26 06:22:30        4347        3672
2018-04-26 10:50:30        3896        3546
2018-04-26 12:04:30        3478        3557
2018-04-26 14:02:30        3625        3598
2018-04-26 15:31:30        3751        3606

我想要做的是让我的日期成为一个列表、数组或系列,我可以在其中迭代列表中的所有元素.这样我就可以使用这些日期来访问另一个数据帧 df_other 中的行,最后将它们附加到一个新的数据帧 df_new:

What I want to do is to get my dates a list, array, or series where I can iterate over all elements in my list. So that I can use those dates to access rows in another dataframe df_other, and in the end append them to a new dataframe df_new:

for date in date_list():
    df_new = df_new.append(df_other.iloc[df_other.index.get_loc(date)])

对于我的列表中的日期应该运行为:

which for a date on my list should be run as:

df_new.append(df_other.iloc[df_other.index.get_loc('2018-04-25 18:37:00')])

我尝试使用 df.index 制作一个列表,但它返回一个 Datetimeindex,其中我只能访问每个日期:

I tried making a list using df.index but that returns a Datetimeindex where I can only access each date as:

display(df.index[0])
Timestamp('2018-04-25 18:37:00')

时间戳部分破坏了我的 .append 调用.

where the Timestamp part ruins my .append call.

也试过 df.index.tolist() 但它返回一个列表:[Timestamp('2018-04-25 18:37:00'), ...]

Also tried df.index.tolist() but that returns a list of: [Timestamp('2018-04-25 18:37:00'), ...]

推荐答案

为什么不直接遍历数据框的行并只使用索引值?

Why don't you just iterate over the rows of the dataframe and just use the index values?

创建数据框:

data = [
['2018-04-25 18:37:00',       5862,        4427],
['2018-04-25 21:36:30',       6421,        4581],
['2018-04-25 22:13:00',       5948,        4779],
['2018-04-26 00:11:30',       5703,        4314],
['2018-04-26 02:27:00',       4988,        3868],
['2018-04-26 04:28:30',       4812,        3823],
['2018-04-26 06:22:30',       4347,        3672],
['2018-04-26 10:50:30',       3896,        3546],
['2018-04-26 12:04:30',       3478,        3557],
['2018-04-26 14:02:30',       3625,        3598],
['2018-04-26 15:31:30',       3751,        3606]
]

data = pd.DataFrame(data, columns=['datetime', 'discharge1', 'discharge2'])
data['datetime'] = data['datetime'].apply(pd.to_datetime)
data = data.set_index('datetime')

然后迭代索引和值:

for index, values in data.iterrows():
    print(index)

输出:

2018-04-25 18:37:00
2018-04-25 21:36:30
2018-04-25 22:13:00
2018-04-26 00:11:30
...

这篇关于迭代日期时间索引中的日期列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆