熊猫:如何将Series的MultiIndex折叠为DateTimeIndex?

时间:2018-08-15 10:28:27

标签: python pandas pandas-groupby

作为Pandas groupby: group by semester的后续工作,我需要将Series的MultiIndex折叠为DateTimeIndex。

我已经看过Collapse Pandas MultiIndex to Single Index,但无济于事。我无法使其正常工作。

系列ser是:

dtime  dtime
2016   1        78.0
       7        79.0
2017   1        73.0
       7        79.0
2018   1        79.0
       7        71.0
Name: values, dtype: float64

如何将dtime折叠为单个DateTimeIndex?

dtime
2016-01-01      78.0
2016-07-01      79.0
2017-01-01      73.0
2017-07-01      79.0
2018-01-01      79.0
2018-07-01      71.0
Name: values, dtype: float64

这是产生我的演示系列ser的代码:

from datetime import *
import pandas as pd
import numpy as np

np.random.seed(seed=1111)
days = pd.date_range(start="2016-02-15", 
                     end="2018-09-12",
                    freq="2W")

df = pd.DataFrame({"dtime":days, "values":np.random.randint(50, high=80, size=len(days))}).set_index("dtime")

# group by semester
year = df.index.year.astype(int)
month = (df.index.month.astype(int) - 1) // 6 * 6 + 1
grouped = df.groupby([year, month])

ser = grouped.describe()[("values", "max")].rename("values")
print(ser)

1 个答案:

答案 0 :(得分:2)

您需要一起将MultiIndexSeries的连接级别转换为datetimes

idx = ser.index.get_level_values(0).astype(str) +  ser.index.get_level_values(1).astype(str)

ser.index = pd.to_datetime(idx, format='%Y%m')
print(ser)
2016-01-01    78.0
2016-07-01    79.0
2017-01-01    73.0
2017-07-01    79.0
2018-01-01    79.0
2018-07-01    71.0
Name: values, dtype: float64

或者:

dates = pd.to_datetime(year.astype(str) + month.astype(str), format='%Y%m')
grouped = df.groupby(dates)

ser = grouped.describe()[("values", "max")].rename("values")
print (ser)
2016-01-01    78.0
2016-07-01    79.0
2017-01-01    73.0
2017-07-01    79.0
2018-01-01    79.0
2018-07-01    71.0
Name: values, dtype: float64