Python中未知大小的二维数组

2024-03-28 20:55:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我是python和numpy的新手,如果问题很明显的话,我很抱歉。在网上我找不到正确的答案。 我需要在python中创建一个未知大小的二维数组(a.ndim-->;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是我需要初始化的数组。


Tags: 方法答案ingtnumpy列表fordata
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]

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

在numpy中,初始化时必须指定数组的大小。稍后,如果需要,可以展开数组。

但请记住,不建议扩展数组,应该作为最后的手段来完成。

Dynamically expanding a scipy array

考虑到你的后续评论,听起来你在试图做如下事情:

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 Tutorials on Dictionaries应该能够给你所寻求的洞察力。

相关问题 更多 >