0

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?

asked Oct 8, 2020 at 7:02
1
  • Just treat it as a list of lists, even do arr.tolist(). Then create the dict from that. Should be a straight forward iteration. Commented Oct 8, 2020 at 7:12

2 Answers 2

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

0

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
answered Oct 8, 2020 at 7:52

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.