Here is the input type, a NumPy array, like
[['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']]
I want to convert it to a JSON file like
{
"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']
}
How to do that?
2 Answers 2
You can use a dictionary comprehension like this:
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']}
answered Oct 8, 2020 at 7:38
Comments
That's how I do that after inspiring by @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
Comments
lang-py
arr.tolist()
. Then create the dict from that. Should be a straight forward iteration.