如何创建遍历集合的数据框? [英] How to create dataframes iterating over a set?

查看:58
本文介绍了如何创建遍历集合的数据框?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个数据框:

d = {'city':['Barcelona','Madrid','Rome','Torino','London','Liverpool','Manchester','Paris'],
'country': ['ES','ES','IT','IT','UK','UK','UK','FR'],
'revenue': [1,2,3,4,5,6,7,8],
'amount': [8,7,6,5,4,3,2,1]
df = pd.DataFrame(d)

我想获取每个国家/地区的信息:

I want to obtain this for each country:

españa = {'city':['Barcelona','Madrid']
          'revenue':[1,2]
          'amount':[8,7]}
 ES = pd.DataFrame(españa)

最后我将有4个数据框,分别为ES,IT,UK和FR.

So that in the end I will have 4 dataframes named ES,IT,UK and FR.

到目前为止,我已经尝试过:

I have tried this so far:

a = set(df.loc[:]["country"])
for country in a:
    country = df.loc[(df["country"]== country),['date','sum']]

但是那只给了我一个带有一个值的数据框.

But that only gave me one dataframe with one value.

推荐答案

您可以对groupby使用字典理解:

You can use a dictionary comprehension with groupby:

res = {k: v.drop('country', 1) for k, v in df.groupby('country')}

print(res)

{'ES':    amount       city  revenue
       0       8  Barcelona        1
       1       7     Madrid        2,
 'FR':    amount   city  revenue
       7       1  Paris        8,
 'IT':    amount    city  revenue
       2       6    Rome        3
       3       5  Torino        4,
 'UK':    amount        city  revenue
       4       4      London        5
       5       3   Liverpool        6
       6       2  Manchester        7}

这篇关于如何创建遍历集合的数据框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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