Python pandas,时间序列,将多列合并成完整的时间戳 PeriodIndex

demo.py(PeriodIndex,将多列合并成完整的时间戳):

# coding=utf-8
import pandas as pd


# DataFrame (时间戳是由多列共同组成的)
df = pd.DataFrame([{"name": "张三", "年": 2018, "月":5, "日":25}, {"name": "李四", "年": 2019, "月":2, "日":10},{"name": "王五", "年": 2019, "月":1, "日":26}])
print(df)
'''
    name   年   日  月
0   张三  2018  25  5
1   李四  2019  10  2
2   王五  2019  26  1
'''

# 根据df的多列组成完整的时间索引(PeriodIndex)
periods = pd.PeriodIndex(year=df["年"], month=df["月"], day=df["日"], freq="D")
print(periods)  # PeriodIndex(['2018-05-25', '2019-02-10', '2019-01-26'], dtype='period[D]', freq='D')

# 可以将PeriodIndex设置为索引。
df2 = df.set_index(periods)
print(df2)   # 时间序列索引
'''
            name    年   日  月
2018-05-25   张三  2018  25  5
2019-02-10   李四  2019  10  2
2019-01-26   王五  2019  26  1
'''
#  然后可以通过时间序列索引进行重采样(分组)统计。

猜你喜欢

转载自blog.csdn.net/houyanhua1/article/details/87891256