我已将此数据帧分组
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的情况下将此输出放入新的数据帧? 例如,如果下次有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
答案 0 :(得分:1)
您可以使用以下方法从groupby对象创建字典:
d = dict(tuple(df1.groupby('City')))
print(d['Portland'])
Name City
2 Mallory Portland
5 Mallory Portland
答案 1 :(得分:0)
您可以使用魔术方法__iter__()
来获取groupby迭代器,并使用dict()
将其转换为字典:
dct = dict(df.groupby('City').__iter__())
如果要从字典中获取单独的数据帧,则可以使用方法values()
:
df1, df2 = dct.values()