0

I am trying to read data from a server like this:

with requests.Session() as s:
    data = {}
    r = s.get('https://something.com' , json = data ).json()
    training_set1 = np.empty([-1,4])
    training_set1[:,0] = r["o"]
    training_set1[:,1] = r["h"]
    training_set1[:,2] = r["l"]
    training_set1[:,3] = r["c"]

But I don't know the length of arrays, so I used -1 then got this error message:

ValueError: negative dimensions are not allowed

How can I fix this code? The response r is a JSON object:

{"t":[1322352000,1322438400], 
 "o":[123,123], 
 "h":[123,123], 
 "l":[123,123], 
 "c":[123,123]}

that I am trying to rearrange it to a numpy array.

Hasani
  • 3,543
  • 14
  • 65
  • 125

2 Answers2

1

Numpy arrays have fixed sizes. You cannot initialize a dynamic sized array. What you can do is use a list of lists and later convert the list to a numpy array.

Something like this should work assuming r["x"] is a list. (Untested code)

with requests.Session() as s:
    data = {}
    r = s.get('https://something.com' , json = data ).json()
    t_set1 = []
    t_set1.append(r["o"])
    t_set1.append(r["h"])
    t_set1.append(r["l"])
    t_set1.append(r["c"])
training_set1 = np.array(t_set1)

Edit: Edited for the order "o","h","l",""c after OP edited the question

Teshan Shanuka J
  • 1,448
  • 2
  • 17
  • 31
1

You cannot declare a numpy array with an unknown dimension. But you can declare it in one single operation:

training_set1 = np.array([r["o"], r["o"], r["h"], r["l"]])

or even better:

training_set1 = np.array([r[i] for i in "oohl"])
Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252