简体   繁体   English

如何在Python中将字典列表的值从字符串转换为浮点数

[英]How to convert the values of a list of dictionaries from a string to a float in Python

I want to change the Values of my Json data from a string to a float. 我想将我的Json数据的值从字符串更改为浮点数。 My example Json is below. 我的示例Json在下面。

  • Doing this returns a list of Value "3" from QN_9. 这样做会从QN_9返回值“ 3”的列表。 How can I return the whole original list but the values are also converted to float instead of list. 如何返回整个原始列表,但值也被转换为float而不是list。
input_dicts = [d["QN_9"]for d in input_dicts]
  • Json File / input_dicts : Json文件/ 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"}]

It should be Something like this "QN_9" : 3 instead of "QN_9" : "3" 应该是这样的东西"QN_9" : 3而不是"QN_9" : "3"

So overall the final result looks like this 总的来说,最终结果看起来像这样

[{"STATIONS_ID": "44", "MESS_DATUM": "2018020800", "QN_9": 3, "TT_TU": -6.6, "RF_TU": 96.0}

You can get your desired result in this process: 您可以在此过程中获得所需的结果:

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}]

Check if the below one works for you. 检查以下一项是否适合您。

If the dictionary is something like below. 如果字典如下所示。

dic = {"QN_9": "3", "QN_10": "10"}

You can convert the keys to float or int using dictionary comprehension. 您可以使用字典理解将键转换为float或int。

{k:int(v) for (k,v) in dic.items()}

The output would be like below. 输出如下。

{'QN_9': 3, 'QN_10': 10}
        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')

I was able to easily do it via Pandas. 我可以通过熊猫轻松地做到这一点。 I think this way is the neater version as the way Sayandip suggested was to convert every thing into a float including the things i needed as strings. 我认为这种方式是更整洁的版本,因为Sayandip建议将所有东西都转换为浮点数,包括我需要作为字符串的东西。 Thank you for the help!~ 谢谢您的帮助!〜

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM