将N个不同的向量排列到对象数组中-而不是矩阵中

时间:2019-07-01 17:46:34

标签: python arrays numpy object vector

在python和/或numpy中: 我有几个一维向量(数组),我一次从文件中读取一个。它们并不都具有相同数量的系数,即不具有相同的长度。我想将每个向量添加到向量列表中,并将其作为对象进行处理,一次将它们吸出一个进行处理。我已经阅读了听起来像以下过程的任何问题/答案: How to build a matrix one column at a time

Vectorized way to arrange vector into matrix (numpy)

并且我尝试了各种python / numpy函数,包括追加,连接,堆栈,使用递增索引追加到对象数组等。例如:

filenames = pd.read_csv('filenames', header=None)
numFiles = filenames.shape[0]

# read in all files
firstTime = True
x0 = [numFiles]
y0 = [numFiles]
for i in range(numFiles):

    fn = filenames.iloc[i, 0]
    df = pd.read_csv(fn, delimiter='\t', header=None)

    # select first two columns in data frame
    nparr = np.array(df)[:,0:2]

    # this one line does a loop, discarding entries with zero flux
    # THIS IS THE PLACE where all vectors wind up with a different length
    nparr = nparr[nparr[:,1] != 0]

    x0[i] = nparr[:,0]
    y0[i] = nparr[:,1]

# by this point, object array is complete

在这种情况下,我尝试使用的任何语法都会产生错误:

Traceback (most recent call last):
  File "InterpolateToSameDMValues-26-Jun-2019.py", line 48, in <module>
    x0[i] = nparr[:,0]
IndexError: list assignment index out of range

否则numpy只是将我所有的向量附加到一个很长的向量中。

如何告诉python不要做任何花哨的事情,而只是创建一个可以迭代的对象数组?

for obj in x0:
    # do something with vector

1 个答案:

答案 0 :(得分:0)

您可以尝试创建向量列表。 列表功能强大append()

import numpy as np
my_list = []
#you can append your list like this
sample_vector = np.array([1, 2, 3])
sample_vector2 = np.array([3, 2, 1])
my_list.append(sample_vector)
my_list.append(sample_vector2)
#working with your stored vectors
for vector in my_list:
    print(vector)
    #or do what you want

希望您会有所想法