【问题标题】:convert numpy array to json将numpy数组转换为json
【发布时间】:2020-10-08 07:02:03
【问题描述】:

这里是输入类型,一个NumPy数组,比如

[['id' '796132' '1148512' '87741691' '87910849' '88188296']
 ['diagnosis' '1' '0' '1' '0' '0']
 ['fractal_dimension_worst' '0.08701' '0.08006' '0.08255' '0.06484' '0.1118']] 

我想把它转换成一个 JSON 文件,比如

{
   "id": ['796132', '1148512', '87741691', '87910849', '88188296'],
   "diagnosis": ['1', '0', '1', '0', '0'],
   "fractal_dimension_worst": ['0.08701', '0.08006', '0.08255', '0.06484', '0.1118']
}

怎么做?

【问题讨论】:

  • 只要把它当作一个列表的列表,即使是arr.tolist()。然后从中创建字典。应该是一个直接的迭代。

标签: python arrays json numpy


【解决方案1】:

您可以像这样使用字典推导:

import numpy as np
arr = np.array([
    ['id', '796132', '1148512', '87741691', '87910849', '88188296'],
    ['diagnosis', '1', '0', '1', '0', '0'],
    ['fractal_dimension_worst', '0.08701', '0.08006', '0.08255', '0.06484', '0.1118']
])

json_dict = {l[0]: list(l[1:]) for l in arr}

>> {'id': ['796132', '1148512', '87741691', '87910849', '88188296'],
 'diagnosis': ['1', '0', '1', '0', '0'],
 'fractal_dimension_worst': ['0.08701',
  '0.08006',
  '0.08255',
  '0.06484',
  '0.1118']}

【讨论】:

    【解决方案2】:

    在受到@hpaulj 的启发后,我就是这样做的。

    import csv
    import numpy as np
    import pandas as pd
    
    # df = pd.read_csv('inf_small.csv')
    
    with open('..\inf.csv', newline='') as csvfile:
        data = list(csv.reader(csvfile, delimiter=','))
    
    npMatrix = np.array(data)
    
    # calculate row and column numbers
    row_count, column_count = npMatrix.shape
    # neglect first row and get new row numbers
    row_count = row_count - 1
    npMatrix = npMatrix.transpose()
    
    # transfer numpy array to list
    matrix = npMatrix.tolist()
    
    # transfer list to that JSON file
    result = {}
    
    for index, item in enumerate(matrix):
        temp = item[0]
        del item[0]
        result[temp] = item
    

    【讨论】:

      猜你喜欢
      • 2016-07-25
      • 2020-10-20
      • 2018-06-03
      • 1970-01-01
      • 2021-12-29
      • 2017-03-08
      • 1970-01-01
      • 2012-04-18
      • 2017-12-15
      相关资源
      最近更新 更多