gpt4 book ai didi

python - Python 中未知大小的二维数组

转载 作者:行者123 更新时间:2023-12-05 03:15:43 25 4
gpt4 key购买 nike

我是 python 和 numpy 的新手,如果问题有点明显,我很抱歉。在互联网上寻找我找不到正确的答案。我需要在 python 中创建一个未知大小的二维 (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 中填充未知大小数组的相当高性能(虽然比初始化为精确大小慢)的方法:

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)并稍后修剪数组。

关于python - Python 中未知大小的二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13500105/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com