将Pandas转换为JVectorMap的mapData

2024-10-03 00:27:09 发布

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

我有一个flask/python站点,它需要将pandas列(CountryCode(“US”)和Value(192656.56))返回到一个html模板,该模板提供一个JVectorMap

mapData必须如下所示:

var gdpData = {
  "AF": 16.63,
  "AL": 11.58,
  "DZ": 158.97,
  ...
};

数据帧看起来像:

enter image description here

如果这个pandas df是一个json列表(请参见-http://api.worldbank.org/v2/country/all/indicator/NY.GDP.PCAP.PP.CD?format=json&mrv=1&per_page=300),那么接下来的python代码工作正常,但是我无法使用pandas数据帧从函数返回格式正确的变量。我已经尝试了十几种循环/打印方法,到目前为止,所有这些方法都破坏了所需的变量输出

mapData = "var mapData = {\n"
for item in y[1]:   
    mapData += item['country']['id'] + ": " + "{:.2f}".format(item['value']) +",\n"
mapData += "}"
print(mapData)

接下来,将此数据添加到Jvector脚本中,如下所示:

function createList(country.value, country.id,indicator.id){
    var gdpData = {
        results.gdpdata   # data to be filled in from the python and pandas df
      };

    $('#world-map-gdp').vectorMap({
    map: 'world_mill',
    series: {
    regions: [{
        values: gdpData,
        scale: ['#C8EEFF', '#0071A4'],
        normalizeFunction: 'polynomial'
    }]
    },
    onRegionTipShow: function(e, el, code){
    el.html(el.html()+' (GDP - '+gdpData[code]+')');
    }
});

}


Tags: 数据模板idjsonpandasdfvarhtml
1条回答
网友
1楼 · 发布于 2024-10-03 00:27:09

我能够通过正则表达式脚本和字符串转储“作弊”并使字符串工作(带有控制台错误)

我发现了一个更好的解决方案,使用pandas自己的“to_json”函数,如下所示。它不是把GDP值拉到地图上,而是说这些值是未定义的,我想我需要查看一些小参数:

def MapData():
    global conn
    import wbdata
    ind_id=1

    qry = "SELECT * FROM indicator WHERE id = '" + str(ind_id) + "' ;"

    cur = conn.cursor()
    df = pd.read_sql(qry, conn)
    cur.close()

    ind_label = "GDP"
    ind_code = "NY.GDP.MKTP.CD"
    indicators = { ind_code : ind_label }

    data = wbdata.get_dataframe(indicators, country=u'all', convert_date=False, keep_levels=True).dropna()

    # Get most recent data only
    data2 = data.reset_index().drop_duplicates(subset='country', keep='first').set_index('country')
    # Merge data with country data from database - this removes
    rslt = pd.merge(data2, df, left_on='country', right_on="name", right_index=False, how='inner', sort=False);

    rslt.reset_index()
    rsl2 = rslt[['iso2c',ind_label]]
    rsl3 = rsl2.dropna()
    rssl = rsl3.round({ind_label:2}) 

    return (pd.DataFrame(rssl).to_json(orient='values')) # see other options for to_json - orient - like columns, records, split, etc.

这将渲染贴图,但gdpData[code]值显示为未定义

enter image description here

注意:Wbdata.get_数据帧。。。小心-慢!为什么?因为这会获取60年(1500行)的数据!!最近仅每个国家需要熊猫.drop_duplicates(subset='country', keep='first')命令 使用本地缓存的文件或数据库摘要可以加快(很多)速度,或者,另一个很好的选择是让Javascript直接从前端获取JSON数据,请参见Using JQuery and online JSON data to populate JVectorMaps

有人能解决这个问题吗

相关问题 更多 >