我有以下数据帧:
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']
}
有没有一种方法可以遍历字典groupby year,找到平均数并创建新的数据帧,命名为dictional中的键
我试过类似的方法,但不起作用
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
更简单的方法是创建一个映射,将大陆作为键/值对中的值。然后将状态列映射替换为大陆列。最后在Continent和year上使用groupby函数,并输出数字列的平均值
您的代码几乎是正确的,只是在
numer
中输入了一个拼写错误,并将结果存储在字典中:印刷品:
相关问题 更多 >
编程相关推荐