Say I have the following dataframe, and want to group-by the ys:
假设我有以下数据框,并希望按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:
我可以很好地遍历这个新的groupby对象,但我希望在以下循环中按组访问的数据帧列表:
for name, group in grouped:
do_something(group)
Is this possible?
这可能吗?
1 个解决方案
#1
7
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]
>>>
#1
7
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]
>>>