我有这个数据框:
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)
我想为每个国家获得这个:
españa = {'city':['Barcelona','Madrid']
'revenue':[1,2]
'amount':[8,7]}
ES = pd.DataFrame(españa)
所以最后我将有 4 个数据框,分别命名为 ES、IT、UK 和 FR。
到目前为止我已经试过了:
a = set(df.loc[:]["country"])
for country in a:
country = df.loc[(df["country"]== country),['date','sum']]
但这只给了我一个具有一个值的数据框。
请您参考如下方法:
您可以使用 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}
