作为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)

最佳答案

您需要一起将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

关于python - Pandas :如何将Series的MultiIndex折叠为DateTimeIndex?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51857052/

10-12 22:25