Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/347.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Numpy连接到空数组_Python_Numpy - Fatal编程技术网

Python Numpy连接到空数组

Python Numpy连接到空数组,python,numpy,Python,Numpy,我正在尝试连接一组从磁盘加载的numpy数组。所有数组都有不同数量的列 这是我的密码 import numpy as np FILE_LIST = ["matrix a", "matrix b"] result=np.array([[0,0],[0,0]]) # I need to avoid this zero matrix for fileName in FILE_LIST: matrix = matrix= np.genfromtxt(fileName, delimiter="

我正在尝试连接一组从磁盘加载的numpy数组。所有数组都有不同数量的列

这是我的密码

import numpy as np

FILE_LIST = ["matrix a", "matrix b"]

result=np.array([[0,0],[0,0]]) # I need to avoid this zero matrix
for fileName in FILE_LIST:
    matrix = matrix= np.genfromtxt(fileName, delimiter=" ")    
    result = np.concatenate((result, matrix),axis=1) 

print result

在这里,我将结果初始化为一个带零的数组,因为我无法连接到空数组。我需要避免在结果开头附加这个零数组。如何实现这一点?

我建议首先加载数组中的所有数据,然后应用numpys
hstack
,以便水平堆叠数组

result = np.hstack([np.genfromtxt(fileName,delimiter=" ") for fileName in FILE_LIST])

不清楚你为什么要避免这种情况。但你可以做到:

result=None
for fileName in FILE_LIST:
    matrix= np.genfromtxt(fileName, delimiter=" ")
    if result is None:
        result = matrix
    else:
        result = np.concatenate((result, matrix),axis=1) 
通常,我们尽量避免重复连接(或附加)到数组,而宁愿附加到列表。但是在本例中,
genfromtxt
是一个足够大的操作,因此如何组合数组无关紧要

有了列表,循环将是:

result=[]
for fileName in FILE_LIST:
    result.append(np.genfromtxt(fileName, delimiter=" "))    
result = np.concatenate(result,axis=1) 
列表理解本质上是一样的