将 Pandas groupby 对象转换为数据框列表 [英] Convert a pandas groupby object to list of dataframes

查看:157
本文介绍了将 Pandas groupby 对象转换为数据框列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下数据框,并希望按 ys 分组:

 xs ys0 0 01 1 02 2 13 3 1

我可以通过运行来做到这一点

grouped = df.groupby('ys')

我可以很好地遍历这个新的 groupby 对象,但是我想要在以下循环中由 group 访问的数据帧列表:

为名称,分组分组:做某事(群)

这可能吗?

解决方案

当然,只需遍历组即可!

<预><代码>>>>将熊猫导入为 pd,将 numpy 导入为 np>>>df = pd.DataFrame(dict(xs=list(range(4)), ys=[0,0,1,1]))>>>dfx ys0 0 01 1 02 2 13 3 1>>>grouped = df.groupby('ys')>>>数据帧 = [分组为 _,分组分组]>>>数据框[ x y y0 0 01 1 0, xs ys2 2 13 3 1]>>>

Say I have the following dataframe, and want to group-by the ys:

   xs  ys
0   0   0
1   1   0
2   2   1
3   3   1

I can do this by running

grouped = df.groupby('ys')

I can iterate through this new groupby object fine, but instead I want a list of the dataframes that are accessed by group in the following loop:

for name, group in grouped:
    do_something(group)

Is this possible?

解决方案

Sure, just iterate over the groups!

>>> import pandas as pd, numpy as np
>>> df = pd.DataFrame(dict(xs=list(range(4)), ys=[0,0,1,1]))
>>> df
   xs  ys
0   0   0
1   1   0
2   2   1
3   3   1
>>> grouped = df.groupby('ys')
>>> dataframes = [group for _, group in grouped]
>>> dataframes
[   xs  ys
0   0   0
1   1   0,    xs  ys
2   2   1
3   3   1]
>>>

这篇关于将 Pandas groupby 对象转换为数据框列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆