问题
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:
var gdpData = {
"AF": 16.63,
"AL": 11.58,
"DZ": 158.97,
...
};
The Dataframe looks like :
If this pandas df was a json list (see - http://api.worldbank.org/v2/country/all/indicator/NY.GDP.PCAP.PP.CD?format=json&mrv=1&per_page=300), this next python code works correctly, but I can't get the properly formatted variable to return from a function - with a pandas dataframe. I've tried a dozen loop / print approaches and all bugger up the desired variable output so far.
mapData = "var mapData = {\n"
for item in y[1]:
mapData += item['country']['id'] + ": " + "{:.2f}".format(item['value']) +",\n"
mapData += "}"
print(mapData)
This data next gets added to a Jvector script as follows:
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]+')');
}
});
}
回答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:
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.
This renders a map but the gdpData[code]
values appear as Undefined
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?
来源:https://stackoverflow.com/questions/61164551/convert-pandas-to-mapdata-for-jvectormap