这是一个完整的例子。
import numpy as npimport pandas as pdimport osfname = 'groupby.h5'# create a framedf = pd.Dataframe({'A': ['foo', 'foo', 'foo', 'foo', 'bar', 'bar', 'bar', 'bar', 'foo', 'foo', 'foo'], 'B': ['one', 'one', 'one', 'two', 'one', 'one', 'one', 'two', 'two', 'two', 'one'], 'C': ['dull', 'dull', 'shiny', 'dull', 'dull', 'shiny', 'shiny', 'dull', 'shiny', 'shiny', 'shiny'], 'D': np.random.randn(11), 'E': np.random.randn(11), 'F': np.random.randn(11)})# create the store and append, using data_columns where I possibily# could aggregatewith pd.get_store(fname) as store: store.append('df',df,data_columns=['A','B','C']) print "store:n%s" % store print "ndf:n%s" % store['df'] # get the groups groups = store.select_column('df','A').unique() print "ngroups:%s" % groups # iterate over the groups and apply my operations l = [] for g in groups: grp = store.select('df',where = [ 'A=%s' % g ]) # this is a regular frame, aggregate however you would like l.append(grp[['D','E','F']].sum()) print "nresult:n%s" % pd.concat(l, keys = groups)os.remove(fname)
输出量
store:<class 'pandas.io.pytables.HDFStore'>File path: groupby.h5/df frame_table (typ->appendable,nrows->11,ncols->6,indexers->[index],dc->[A,B,C])df: A B C D E F0 foo one dull -0.815212 -1.195488 -1.3469801 foo one dull -1.111686 -1.814385 -0.9743272 foo one shiny -1.069152 -1.926265 0.3603183 foo two dull -0.472180 0.698369 -1.0070104 bar one dull 1.329867 0.709621 1.8778985 bar one shiny -0.962906 0.489594 -0.6630686 bar one shiny -0.657922 -0.377705 0.0657907 bar two dull -0.172245 1.694245 1.3741898 foo two shiny -0.780877 -2.334895 -2.7474049 foo two shiny -0.257413 0.577804 -0.15931610 foo one shiny 0.737597 1.979373 -0.236070groups:Index([bar, foo], dtype=object)result:bar D -0.463206 E 2.515754 F 2.654810foo D -3.768923 E -4.015488 F -6.110789dtype: float64
一些警告:
1)如果您的组密度相对较低,则此方法很有意义。大约数百或数千个组。如果获得的收益更多,则效率更高(但方法更复杂),并且您正在应用的函数(在这种情况下
sum)将变得更加严格。
本质上,您将按块对整个商店进行迭代,然后按组进行分组,但将组仅进行半折叠(想象一下是做一个均值,因此您需要保持运行总数和运行计数,然后在最后进行除法)
。因此,某些 *** 作会有些棘手,但可能会处理许多组(而且速度非常快)。
2)可以通过保存坐标(例如组位置,但是稍微复杂一点)来提高效率。
3)上面的方案无法进行多重分组(有可能,但是需要一种类似于2的方法)
4)您要分组的列,必须是data_column!
5)您可以在选择的btw中组合您想要的任何其他过滤器(这是进行多组btw的时髦方法,您仅在它们的乘积上形成2个唯一的group和iterator列表,如果有很多,效率就不是很高组,但可以工作)
高温超导
让我知道这是否适合您
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)