我想将我的Json数据的值从字符串更改为浮点型。我的示例Json在下面。
input_dicts = [d["QN_9"]for d in input_dicts]
[{"STATIONS_ID": "44", "MESS_DATUM": "2018020800", "QN_9": "3", "TT_TU": "-6.6", "RF_TU": "96.0"}, {"STATIONS_ID": "44", "MESS_DATUM": "2018020801", "QN_9": "3", "TT_TU": "-6.8", "RF_TU": "98.0"}]
应该是这样的"QN_9" : 3
而不是"QN_9" : "3"
总的来说,最终结果看起来像这样
[{"STATIONS_ID": "44", "MESS_DATUM": "2018020800", "QN_9": 3, "TT_TU": -6.6, "RF_TU": 96.0}
答案 0 :(得分:1)
检查以下一项是否适合您。
如果字典如下所示。
dic = {"QN_9": "3", "QN_10": "10"}
您可以使用字典理解将键转换为float或int。
{k:int(v) for (k,v) in dic.items()}
输出如下。
{'QN_9': 3, 'QN_10': 10}
答案 1 :(得分:1)
您可以在此过程中获得所需的结果:
input_dict = [{"STATIONS_ID": "44", "MESS_DATUM": "2018020800", "QN_9": "3", "TT_TU": "-6.6", "RF_TU": "96.0"}, {"STATIONS_ID": "44", "MESS_DATUM": "2018020801", "QN_9": "3", "TT_TU": "-6.8", "RF_TU": "98.0"}]
output_dict = [{key:float(elem[key]) for key in elem} for elem in input_dict]
>>> output_dict
[{'STATIONS_ID': 44.0,
'MESS_DATUM': 2018020800.0,
'QN_9': 3.0,
'TT_TU': -6.6,
'RF_TU': 96.0},
{'STATIONS_ID': 44.0,
'MESS_DATUM': 2018020801.0,
'QN_9': 3.0,
'TT_TU': -6.8,
'RF_TU': 98.0}]
答案 2 :(得分:0)
df = pd.DataFrame(input_dicts)
df['STATIONS_ID'] = df['STATIONS_ID'].astype(str)
df['MESS_DATUM'] = pd.to_datetime(df['MESS_DATUM'], format='%Y%m%d%H')
df['QN_9'] = df['QN_9'].astype(int)
df['TT_TU'] = df['TT_TU'].astype(float)
df['RF_TU'] = df['RF_TU'].astype(float)
return func.HttpResponse(df.to_json(orient='records'), mimetype='application/json')
我能够通过Pandas轻松地做到这一点。我认为这种方式是更整洁的版本,因为Sayandip建议将所有东西都转换为浮点数,包括我需要作为字符串的东西。谢谢您的帮助!〜