Python用列表值循环字典

时间:2020-09-14 08:48:39

标签: python loops dictionary group-by

我有以下数据框:

    data = {'state': ['Rome', 'Venice', 'NY', 'Boston', 'London', 'Bristol'],
    'year': [2000, 2001, 2002, 2001, 2003, 2003],
    'number': [1.5, 1.7, 3.6, 2.4, 2.9, 3.2]}

df = pd.DataFrame(data)

并根据以下内容创建字典:

dic = {
    'it':['Rome', 'Venice'], 
    'UK':['London', 'Bristol'],
    'US':['NY', 'Boston']
}

是否有一种方法可以逐年对字典进行遍历,查找均值并创建新的数据框(称为字典中的键)。

我已经尝试过类似的操作,但是无法正常工作。...

for x, y in dic.items():
    x = df[df['state'].isin(y)].groupby(['year'], as_index=False)['numer'].mean()

例如,英国的预期产出如下:

UK

    year    number
0   2003    3.05

2 个答案:

答案 0 :(得分:2)

您的代码几乎是正确的,只需在numer中输入一个错字,然后将结果存储在字典中即可。

import pandas as pd

data = {'state': ['Rome', 'Venice', 'NY', 'Boston', 'London', 'Bristol'],
    'year': [2000, 2001, 2002, 2001, 2003, 2003],
    'number': [1.5, 1.7, 3.6, 2.4, 2.9, 3.2]}

dic = {
    'it':['Rome', 'Venice'],
    'UK':['London', 'Bristol'],
    'US':['NY', 'Boston']
}

df = pd.DataFrame(data)

out = {}
for x, y in dic.items():
    out[x] = df[df['state'].isin(y)].groupby(['year'], as_index=False)['number'].mean()

for country, df in out.items():
    print(country)
    print(df)
    print('-' * 80)

打印:

it
   year  number
0  2000     1.5
1  2001     1.7
--------------------------------------------------------------------------------
UK
   year  number
0  2003    3.05
--------------------------------------------------------------------------------
US
   year  number
0  2001     2.4
1  2002     3.6
--------------------------------------------------------------------------------

答案 1 :(得分:0)

一种更简单的方法是使用大洲作为键/值对中的值来创建映射。然后,将状态列的映射替换为大洲列。最后在continent和year上使用groupby函数,并输出数字列的平均值

data = {'state': ['Rome', 'Venice', 'NY', 'Boston', 'London', 'Bristol'],
'year': [2000, 2001, 2002, 2001, 2003, 2003],
'number': [1.5, 1.7, 3.6, 2.4, 2.9, 3.2]}

mapping = {
'Rome':'it', 
'Venice':'it',
'London':'UK',
'Bristol':'UK',
'NY':'US',
'Boston':'US'
}

df = pd.DataFrame(data)
df['continent']=df['state'].replace(mapping)
print(df.head())
print(df.groupby(['continent','year'])['number'].mean())