Skip to content Skip to sidebar Skip to footer

Convert Pandas To Mapdata For Jvectormap

I have a flask/python site that needs to return pandas columns - CountryCode ('US') and Value (192656.56) - to an html template that presents a JVectorMap mapData must look like:

Solution 1:

I was able to "cheat" and make a string work (with console errors) via a Regex script and pandas string dump.

I found a better solution using pandas' own "to_json" function as follows. It is not pulling up the GDP values to the map however - it is saying the Values are Undefined - I assume I need to tweek some small parameter:

defMapData():
    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.

This renders a map but the gdpData[code] values appear as Undefined

enter image description here

Note RE: Wbdata.get_dataframe ... Caution - SLOW! Why? Because this fetches 60-years (1500 lines) of data !! Most-Recent-Only per-country needs pandas' .drop_duplicates(subset='country', keep='first') command This can be sped up (a lot) by using a locally cached file, or database summary - or, another great option is by asking Javascript to fetch JSON data directly from the frontend - see Using JQuery and online JSON data to populate JVectorMaps

Does anyone have a solution for this?

Post a Comment for "Convert Pandas To Mapdata For Jvectormap"