看过来
《pandas 教程》 持续更新中,提供建议、纠错、催更等加作者微信: gr99123(备注:pandas教程)和关注公众号「盖若」ID: gairuo。跟作者学习,请进入 Python学习课程。欢迎关注作者出版的书籍:《深入浅出Pandas》 和 《Python之光》。
(编码题)行政部从旧系统导出 2024-08-01 至 2024-08-10 的每日门禁异常次数,但时间顺序完全被打乱:
import pandas as pd
import numpy as np
# 故意乱序的时间索引
idx = pd.to_datetime([
'2024-08-07', '2024-08-02', '2024-08-10', '2024-08-01',
'2024-08-09', '2024-08-05', '2024-08-04', '2024-08-08',
'2024-08-03', '2024-08-06'
])
anomaly = pd.Series(np.random.randint(0, 5, 10), index=idx, name='异常次数')
要求:
sort_index()
将 anomaly
按日期升序重新排序。2024-08-01
。代码如下:
anomaly_sorted = anomaly.sort_index()
print(anomaly_sorted)
示例输出:
2024-08-01 2
2024-08-02 1
2024-08-03 0
2024-08-04 3
2024-08-05 1
2024-08-06 2
2024-08-07 0
2024-08-08 1
2024-08-09 2
2024-08-10 4
Freq: D, Name: 异常次数, dtype: int64
(完)
更新时间:2025-08-21 11:30:25 标签:pandas python 时间索引 顺序