我正在尝试对pandas数据帧进行降采样以减少粒度。例如,我要减少此数据框:
1 2 3 4
2 4 3 3
2 2 1 3
3 1 3 2
对此(使用均值进行下采样以获得2x2数据帧):
2.25 3.25
2 2.25
是否有内置的方法或有效的方法来完成它,或者我必须自己编写?
谢谢
一种选择是使用groupby两次。一次索引:
In [11]: df.groupby(lambda x: x//2).mean()
Out[11]:
0 1 2 3
0 1.5 3.0 3 3.5
1 2.5 1.5 2 2.5
然后一次进入列:
In [12]: df.groupby(lambda x: x//2).mean().groupby(lambda y: y//2, axis=1).mean()
Out[12]:
0 1
0 2.25 3.25
1 2.00 2.25
注意:一个只计算一次均值的解决方案可能是更可取的……一种选择是堆栈,groupby,均值和非堆栈,但是atm有点儿麻烦。
这似乎比Vicktor的解决方案快得多:
In [21]: df = pd.DataFrame(np.random.randn(100, 100))
In [22]: %timeit df.groupby(lambda x: x//2).mean().groupby(lambda y: y//2, axis=1).mean()
1000 loops, best of 3: 1.64 ms per loop
In [23]: %timeit viktor()
1 loops, best of 3: 822 ms per loop
实际上,Viktor的解决方案使我的(动力不足的)笔记本电脑崩溃,从而无法使用更大的DataFrame:
In [31]: df = pd.DataFrame(np.random.randn(1000, 1000))
In [32]: %timeit df.groupby(lambda x: x//2).mean().groupby(lambda y: y//2, axis=1).mean()
10 loops, best of 3: 42.9 ms per loop
In [33]: %timeit viktor()
# crashes
正如Viktor所指出的那样,这不适用于非整数索引,如果需要的话,您可以将它们存储为临时变量,并在之后将其反馈回来:
df_index, df_cols, df.index, df.columns = df.index, df.columns, np.arange(len(df.index)), np.arange(len(df.columns))
res = df.groupby(...
res.index, res.columns = df_index[::2], df_cols[::2]
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句