Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding an array to a numpy array

I'd like to have a numpy array that looks something like this:

X = np.array([[10, 20], [20, 25], [30, 16], [40, 18], [50, 90], [60, 87]])

I currently have dictionary values that I retrieve from firestore:

doc_ref = db.collection('CPU Logs')
query_ref = doc_ref.where(u'testData', u'==', True).order_by(u'logId')
docs = query_ref.get()

I loop through them and assign the key values to 2 variables, id and usage, before adding them to an array toAppend:

for doc in docs:
    values = doc.to_dict()
    id = values['logId']
    usage = values['usage']
    toAppend = [id, usage]

toAppend would look something like [10, 30] if the id were 10 and the usage were 30. Now, I'm having trouble trying to add it to an empty numpy array. I've tried inserting:

X = np.array([])
for doc in docs:
    values = doc.to_dict()
    id = values['logId']
    usage = values['usage']
    toAppend = [id, usage]
    a = X.flatten()
    np.insert(a, [0,0], toAppend)

print(X)

as well as appending:

np.append(X, toAppend)

But both don't seem to work, as the print statement just prints out [].

like image 916
cosmo Avatar asked Nov 03 '25 14:11

cosmo


1 Answers

Have a look at the docs for insert and flatten: They both return new arrays (copies). So you need to write

X = np.insert(a, [0, 0], toAppend)

in order for X to contain the extended array. I also don't think you need the preceding X.flatten().

Instead of inserting into a numpy array (which is expensive), you should consider just building a nested list and only convert it once at the end.

like image 86
IonicSolutions Avatar answered Nov 06 '25 05:11

IonicSolutions



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!