从分组的数据帧自动生成新的数据帧

2024-03-28 17:32:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我已将此数据帧分组


df1 = pd.DataFrame( { 
    "Name" : ["Alice", "Bob", "Mallory", "Mallory", "Bob" , "Mallory"] , 
    "City" : ["Seattle", "Seattle", "Portland", "Seattle", "Seattle", "Portland"] } )



group = df1.groupby('City')

for city, city_df in group:
    print(city)

    print(city_df)

如何在不指定新dfs的情况下将此输出转换为新的数据帧? 比如如果a下次有4个组,我想自动得到4个dfs

Portland
      Name      City
2  Mallory  Portland
5  Mallory  Portland
Seattle
      Name     City
0    Alice  Seattle
1      Bob  Seattle
3  Mallory  Seattle
4      Bob  Seattle


Tags: 数据namecitydfgrouppdbobdf1
2条回答

您可以使用魔法方法__iter__()获取groupby迭代器,并将其转换为具有dict()的字典:

dct = dict(df.groupby('City').__iter__())

如果要从字典中获取单独的数据帧,可以使用values()方法:

df1, df2 = dct.values()

您可以从groupby对象创建字典,方法是:

d = dict(tuple(df1.groupby('City')))

print(d['Portland'])

    Name      City
2  Mallory  Portland
5  Mallory  Portland

相关问题 更多 >