将数组添加到numpy数组 [英] Adding an array to a numpy array
问题描述
我想要一个看起来像这样的numpy数组:
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]])
我目前有一些从firestore中检索到的字典值:
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()
我遍历它们并将键值分配给2个变量id
和usage
,然后再将它们添加到数组toAppend
中:
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]
如果id为10,用法为30,则
toAppend看起来类似于[10, 30]
.现在,我很难尝试将其添加到一个空的numpy数组中.我尝试插入:
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)
以及附加:
np.append(X, toAppend)
但是两者似乎都不起作用,因为print语句仅打印出[]
.
But both don't seem to work, as the print statement just prints out []
.
推荐答案
看看 flatten
:它们都返回新的数组(副本).所以你需要写
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)
,以便X
包含扩展数组.我也不认为您需要前面的X.flatten()
.
in order for X
to contain the extended array. I also don't think you need the preceding X.flatten()
.
您应该考虑只构建一个嵌套的list
,最后只将其转换一次,而不是插入一个numpy数组(这很昂贵).
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.
这篇关于将数组添加到numpy数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!