我的初始数据框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')
Timestamp 部分破坏了我的 .append 调用。
还尝试了 df.index.tolist() 但返回列表:[Timestamp('2018-04-25 18:37:00'), ...]
请您参考如下方法:
为什么不直接遍历数据帧的行并只使用索引值呢?
创建数据框:
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
...
