【发布时间】:2019-02-15 19:02:50
【问题描述】:
在这里,我的代码实现了文本文件的值;并将矩阵创建为多维数组,但问题是代码创建了更多的二维数组,我无法操作,我需要二维数组,我该怎么做?
解释我的代码的算法:
代码的Moto:我的代码从特定文件夹中获取值,每个文件夹包含7个'txt'文件,从一个用户生成,这样多个文件夹包含多个用户的多个数据。
step1: 启动第一个for循环,并使用特定文件夹中有多少个文件夹来控制它,并在变量'path'中存储第一个文件夹的第一个路径。
step2:使用第二个for循环打开路径并获取7个txt文件的数据。完成后,它关闭第二个for循环并执行其余代码。
step3:将7个txt文件的数据拼接到一个一维数组中。
step4: 使用获取2个文件夹的数据创建二维数组
第5步(这里出现问题):在二维数组ind插入id数组中创建一行
import numpy as np
import array as arr
import os
f_path='Result'
array_control_var=0
#for feacth directory path
for (path,dirs,file) in os.walk(f_path):
if(path==f_path):
continue
f_path_1= path +'\page_1.txt'
#Get data from page1 indivisualy beacuse there string type data exiest
pgno_1 = np.array(np.loadtxt(f_path_1, dtype='U', delimiter=','))
#only for page_2.txt
f_path_2= path +'\page_2.txt'
with open(f_path_2) as f:
str_arr = ','.join([l.strip() for l in f])
pgno_2 = np.asarray(str_arr.split(','), dtype=int)
#using loop feach data from those text file.datda type = int
for j in range(3,8):
#store file path using variable
txt_file_path=path+'\page_'+str(j)+'.txt'
if os.path.exists(txt_file_path)==True:
#genarate a variable name that auto incriment with for loop
foo='pgno_'+str(j)
else:
break
#pass the variable name as string and store value
exec(foo + " = np.array(np.loadtxt(txt_file_path, dtype='i', delimiter=','))")
#marge all array from page 2 to rest in single array in one dimensation
f_array=np.concatenate((pgno_2,pgno_3,pgno_4,pgno_5,pgno_6,pgno_7), axis=0)
#for first time of the loop assing this value
if array_control_var==0:
main_f_array=f_array
if array_control_var==1:
#here use np.array()
main_f_array=np.array([main_f_array,f_array])
else:
main_f_array=np.insert(main_f_array, array_control_var, f_array, 0)
array_control_var+=1
print(main_f_array)
我想要这样的输出
初始 [[0,0,0],[0,0,0,]]
插入后 [[0,0,0],[0,0,0],[0,0,0]]
但输出是
[array([0, 0, 0]) array([0, 0, 0]) 0 0 0]
【问题讨论】:
-
重复
insert(或附加等)到数组是一种不好的做法。很难做到正确,而且速度很慢。将您的值收集在一个列表中,并在最后创建一次数组。 -
其实这不可能,我从文本文件中获取数据,函数返回numpy.array类型,我如何获取数据作为列表?
-
收集列表中的数组
标签: python arrays numpy multidimensional-array insert