按国家和y分组的加权平均值

2024-05-16 10:25:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个代码,它调用了联合国comtrade数据库中的几个API,这些API迭代了几年。然后将这些数据添加到一个包含1991年至2018年所有记者和年份的数据集中。然后我试着得到每个国家每年的贸易价值的平均值,用净重加权。你知道吗

import requests
import pandas as pd
import json
import numpy as np

base = "http://comtrade.un.org/api/get?"
maxrec = "50000"
item = "C"
freq = "A"
px="H0"
ps="all"
r="all"
p="0"
rg="2"
cc="AG2"
fmt="json"

comtrade = pd.DataFrame(columns=['Year', 'Reporter Code', 'Reporter', 'Commodity Code', 'Commodity', 'Trade Value (US$)'])

for year in range(1991,2018):
    print(r)
    ps="{}".format(year)
    url = base + "max=" + maxrec + "&" "type=" + item + "&" + "freq=" + freq + "&" + "px=" +px + "&" + "ps=" + str(ps) + "&" + "r="+ str(r) + "&" + "p=" + p + "&" + "rg=" +rg + "&" + "cc=" + cc + "&" + "fmt=" + fmt
#    print(url)
    t = requests.get(url)
    x = t.json()
    new = pd.DataFrame(x["dataset"])
    comtrade = comtrade.append(new)
group = comtrade.groupby([ 'rtCode', 'yr'])
finalvalue = group.apply(lambda x: np.average(x['TradeValue'], 
weights=x['NetWeight']))

这可能很明显,但问题似乎就在这里:

group = comtrade.groupby([ 'rtCode', 'yr'])
finalvalue = group.apply(lambda x: np.average(x['TradeValue'], weights=x['NetWeight']))

我得到一个错误:

TypeError: unsupported operand type(s) for +: 'NoneType' and 'NoneType'

Tags: 数据importapijsonurlnpgrouprg
1条回答
网友
1楼 · 发布于 2024-05-16 10:25:57

正如您在this example URL from your scraping的下面的描述中所看到的,null是数据的一个主要特性,在您的数据框中输入为“None”。你知道吗

您可以使用Pandas中的“fillna”更改None类型。在本例中,我使用了0,它可以与您的groupby一起使用,或者您也可以使用“nan”,因为根据文档“groupby中的NA组被自动排除”。你知道吗

from numpy import nan
comtrade =  comtrade.fillna(value=0, inplace=True)

enter image description here

相关问题 更多 >