Python中大小未知的二维数组

3

我在Python和Numpy方面还很新,如果问题显而易见,敬请原谅。在网上搜索时,我找不到正确的答案。

我需要在Python中创建一个未知大小的2维数组(a.ndim -->2)。是否可能?我已经找到了一种通过列表传递1维的方法,但对于2维没有成功。

例子:

for i in range(0,Nsens):
    count=0
    for l in range (0,my_data.shape[0]):
        if my_data['Node_ID'][l]==sensors_name[i]:
            temp[count,i]=my_data['Temperature'][l]
            count=count+1
        else:
            count=count

temp是我需要初始化的数组。


我自己也是很新的。我认为你最好通过查看NumPy模块以及它如何处理多维数组来帮助自己。(技术上讲,Python没有多维数组。但是,你可以使用列表的列表来实现。) - bob.sacamento
2
我会先将数据存储到一个1维数组的字典中,以传感器名称作为键。然后在读取所有数据时,我会构建一个2维数组,这时你就知道有多少个传感器了。 - yosukesabai
从你的示例中我所看到的,也许你的代码可以进行向量化处理,你不需要使用循环,而是可以通过索引获取结果数组。如果你能提供一些示例数据会很有帮助。 - bmu
3个回答

3
这展示了在numpy中填充未知大小的数组的一种相对高性能(尽管比初始化到确切大小要慢)的方法:
data = numpy.zeros( (1, 1) )
N = 0
while True:
    row = ...
    if not row: break
    # assume every row has shape (K,)
    K = row.shape[0]
    if (N >= data.shape[0]):
        # over-expand: any ratio around 1.5-2 should produce good behavior
        data.resize( (N*2, K) )
    if (K >= data.shape[1]):
        # no need to over-expand: presumably less common
        data.resize( (N, K+1) )
    # add row to data
    data[N, 0:K] = row

# slice to size of actual data
data = data[:N, :]

适应您的情况:

if count > temp.shape[0]:
    temp.resize( (max( temp.shape[0]*2, count+1 ), temp.shape[1]) )
if i > temp.shape[1]:
    temp.resize( (temp.shape[0], max(temp.shape[1]*2, i+1)) )
# now safe to use temp[count, i]

您可能还需要跟踪实际数据大小(最大计数,最大 i),并稍后修剪数组。


@user1842972:答案中的代码是否对您有用?如果是,请记得接受答案。 - Alex I

1
根据您的后续评论,似乎您正在尝试做以下类似的事情:
arr1 = { 'sensor1' : ' ', 'sensor2' : ' ', 'sensor_n' : ' ' }   #dictionary of sensors (a blank associative array)
                                                                #take not of the curly braces '{ }'
                                                                #inside the braces are key : value pairs
arr1['sensor1'] = 23
arr1['sensor2'] = 55
arr1['sensor_n'] = 125

print arr1

for k,v in arr1.iteritems():
    print k,v

for i in arr1:
    print arr1[i]

Python字典教程可以帮助你获得你所寻求的洞见。


0
在numpy中,您必须在初始化时指定数组的大小。如果需要,稍后可以扩展数组。
但请记住,扩展数组并不推荐,应该作为最后的手段。 动态扩展scipy数组

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接