我正在尝试对数据帧进行重采样。首先,我希望在结果中保留几个聚合。其次,对于特定的列,有一个额外的感兴趣的聚合。由于此聚合仅与单个列相关,因此可以将重采样器限制为此列,以便不必要地将聚合应用于其他列。
这个场景适用于一个简单的一维列索引:
import numpy as np
import pandas as pd
df = pd.DataFrame(data=np.random.rand(50,4), index=pd.to_datetime(np.arange(0, 50), unit="s"), columns=["a", "b", "c", "d"])
r = df.resample("10s")
result = r.aggregate(["mean", "std"])
result[("d", "ffill")] = r["d"].ffill()
print(result)然而,当我开始使用多索引列时,问题就出现了。首先,我不能同时保留多个聚合:
df.columns = pd.MultiIndex.from_product([("a", "b"), ("alpha", "beta")])
r = df.resample("10s") # can be omitted
result = r.aggregate(["mean", "std"])
---> AttributeError: 'Series' object has no attribute 'columns'其次,重采样器不能再局限于相关列:
r[("b", "beta")].ffill()
--> KeyError: "Columns not found: 'b', 'beta'"我如何将我的关注点从简单的指数转变为多指数?
发布于 2019-09-10 23:41:21
您可以在groupby中使用pd.Grouper而不是重采样,例如:
result = df.groupby(pd.Grouper(freq='10s',level=0)).aggregate(["mean", "std"])
print (result)
a b \
alpha beta alpha
mean std mean std mean
1970-01-01 00:00:00 0.460569 0.312508 0.476511 0.260534 0.479577
1970-01-01 00:00:10 0.441498 0.315277 0.487855 0.306068 0.535842
1970-01-01 00:00:20 0.569884 0.248503 0.320552 0.288479 0.507755
1970-01-01 00:00:30 0.478037 0.262654 0.552214 0.251581 0.505132
1970-01-01 00:00:40 0.611227 0.328916 0.473773 0.241604 0.358298
beta
std mean std
1970-01-01 00:00:00 0.357493 0.448487 0.294432
1970-01-01 00:00:10 0.259145 0.472250 0.320954
1970-01-01 00:00:20 0.369490 0.432944 0.150473
1970-01-01 00:00:30 0.298759 0.381614 0.248785
1970-01-01 00:00:40 0.203831 0.381412 0.374965 对于第二部分,我不确定你的意思,但是根据在单列级别的情况下给出的结果,试试这个,它给出了一个结果
result[("b", "beta",'ffill')] = df.groupby(pd.Grouper(freq='10s',level=0))[[("b", "beta")]].first()发布于 2019-09-10 23:37:38
这一定是aggregate中的错误。一个不错的选择是stack
(df.stack().groupby(level=-1)
.apply(lambda x:x.resample('10s', level=0).aggregate(["mean", "std"]))
.unstack(level=0)
)https://stackoverflow.com/questions/57873813
复制相似问题