[英]Convert DataFrameGroupBy object to DataFrame pandas
I had a dataframe and did a groupby in FIPS and summed the groups that worked fine.我有一个数据框并在 FIPS 中做了一个 groupby 并总结了工作正常的组。
kl = ks.groupby('FIPS')
kl.aggregate(np.sum)
I just want a normal Dataframe back but I have a pandas.core.groupby.DataFrameGroupBy
object.我只想要一个普通的 Dataframe,但我有一个
pandas.core.groupby.DataFrameGroupBy
对象。
The result of kl.aggregate(np.sum)
is a normal DataFrame, you just have to assign it to a variable to further use it. kl.aggregate(np.sum)
的结果是一个普通的 DataFrame,你只需要将它分配给一个变量以进一步使用它。 With some random data:使用一些随机数据:
>>> df = DataFrame({'A' : ['foo', 'bar', 'foo', 'bar',
>>> 'foo', 'bar', 'foo', 'foo'],
... 'B' : ['one', 'one', 'two', 'three',
... 'two', 'two', 'one', 'three'],
... 'C' : randn(8), 'D' : randn(8)})
>>> grouped = df.groupby('A')
>>> grouped
<pandas.core.groupby.DataFrameGroupBy object at 0x04E2F630>
>>> test = grouped.aggregate(np.sum)
>>> test
C D
A
bar -1.852376 2.204224
foo -3.398196 -0.045082
df_g.apply(lambda x: x)
将返回原始数据帧。
Using pd.concat
, just like this:使用
pd.concat
,就像这样:
pd.concat(map(lambda x: x[1], groups))
Or also keep index
aligned:或者也保持
index
对齐:
pd.concat(map(lambda x: x[1], groups)).sort_index()
You can output the results of the groupby
with a .head('# of rows')to a variable.您可以使用 .head('# of rows') 将
groupby
的结果输出到变量。
Ex: df2 = grouped.head(100)
例如:
df2 = grouped.head(100)
Now you have a Pandas data frame "df2" with all your grouped data.现在您有一个包含所有分组数据的 Pandas 数据框“df2”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.