【问题标题】:Iterating over a list of dates from datetime index从日期时间索引迭代日期列表
【发布时间】:2018-10-22 21:23:34
【问题描述】:

我的初始数据框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

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

我列表上的日期应该运行为:

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

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

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

时间戳部分破坏了我的.append 通话。

还尝试了df.index.tolist(),但返回的列表如下:[Timestamp('2018-04-25 18:37:00'), ...]

【问题讨论】:

  • 对不起,我不明白这个问题。为什么这些输出对您有问题?你在这里期待什么?
  • 您需要df.index.to_pydatetime() 吗?

标签: python pandas


【解决方案1】:

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

创建数据框:

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
...

【讨论】:

  • 谢谢!由于某种原因,我没有以正确的方式使用 iterrows。
  • @JohanR 如果这是您要查找的内容,您可以通过将灰色按钮标记为绿色来接受答案,以便其他搜索类似查询的人受益
  • @VivekKalyanarangan 啊,谢谢。刚接触这个网站,所以甚至不知道我能做到这一点^.^
  • ", values" 语法有什么作用?当我不使用它时, print(index) 将打印整行数据,而不仅仅是索引中的日期。
  • @Scott DataFrame.iterrows() 返回一个包含两个对象的元组,索引值和包含数据的系列。因此,通过使用“索引、值”,您可以将索引和数据分开。就像您在 data.iterrows() 中执行 "for row: index=row[0] values=row[1]
猜你喜欢
  • 1970-01-01
  • 2021-12-29
  • 2017-08-13
  • 2015-10-20
  • 2017-09-04
  • 1970-01-01
  • 2022-08-14
  • 1970-01-01
  • 2020-06-02
相关资源
最近更新 更多