我有一个
DataFrame
MultiIndex
. 第一级是
DatetimeIndex
每周一次。第二层是
在第一个级别上跨组一致。
我想按月份对第一个级别进行分组,并在第一周进行行处理。
安装程序
midx = pd.MultiIndex.from_arrays([
pd.date_range('2018-01-01', freq='W', periods=10).repeat(2),
list('ABCDEFGHIJ' * 2)
], names=['Date', 'Thing'])
df = pd.DataFrame(dict(Col=np.arange(10, 30)), midx)
预期结果
df
Col
Date Thing
2018-01-07 A 10 # This is the first week
B 11 # of January 2018
2018-01-14 C 12
D 13
2018-01-21 E 14
F 15
2018-01-28 G 16
H 17
2018-02-04 I 18 # This is the first week
J 19 # of February 2018
2018-02-11 A 20
B 21
2018-02-18 C 22
D 23
2018-02-25 E 24
F 25
2018-03-04 G 26 # This is the first week
H 27 # of March 2018
2018-03-11 I 28
J 29
Col
Date Thing
2018-01-07 A 10 # This is the first week
B 11 # of January 2018
2018-02-04 I 18 # This is the first week
J 19 # of February 2018
2018-03-04 G 26 # This is the first week
H 27 # of March 2018
尝试
df.unstack().asfreq('M', 'ffill').stack()
Col
Date Thing
2018-01-31 G 16.0
H 17.0
2018-02-28 E 24.0
F 25.0
这在几个层面上都是错误的。
-
-
事情不是从正确的日期开始的。注意我想要
['A', 'B']
从
'2018-01-07'
['G', 'H']
.
-
asfreq
但这会导致
nan
并皈依
float
-
我不知道发生了什么事
March 2018