如何将多维数组转换为二维数组 [英] How convert multidimensional array to two dimensional array

查看:188
本文介绍了如何将多维数组转换为二维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这里,我的代码专长于价值形式的文本文件;并将矩阵创建为多维数组,但问题是代码创建了更多的二维数组,我无法操作,我需要二维数组,我该怎么做?

解释我的代码的算法:

代码主题:我的代码从特定文件夹中获取值,每个文件夹包含 7 个txt"文件,由一个用户生成,这样多个文件夹包含多个用户的多个数据.

step1:开始第一个for循环,并使用特定文件夹中有多少文件夹来控制它,并在变量'path'中存储第一个文件夹的第一个路径.

step2:使用第二个for循环打开路径并获取7个txt文件的数据.完成后,关闭第二个for循环并执行其余代码.

step3:将7个txt文件的数据拼接成一个一维数组.

step4(这里出现问题):将每个文件夹的一维数组存储为二维数组.先结束循环.

代码:

将 numpy 导入为 np从数组导入 *导入操作系统f_path='结果'array_control_var=0#for feachh 目录路径for (path,dirs,file) in os.walk(f_path):如果(路径== f_路径):继续f_path_1= 路径 +'\page_1.txt'#从第 1 页单独获取数据,因为那里有字符串类型的数据.pgno_1 = np.array(np.loadtxt(f_path_1, dtype='U', delimiter=','))#仅适用于 page_2.txtf_path_2= 路径 +'\page_2.txt'使用 open(f_path_2) 作为 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对于范围内的 j(3,8):#使用变量存储文件路径txt_file_path=path+'\page_'+str(j)+'.txt'如果 os.path.exists(txt_file_path)==True:#genarate一个变量名,用for循环自动增加foo='pgno_'+str(j)别的:休息#将变量名作为字符串传递并存储值exec(foo + " = np.array(np.loadtxt(txt_file_path, dtype='i', delimiter=','))")#z=np.array([pgno_2,pgno_3,pgno_4,pgno_5,pgno_6,pgno_7])#marge 从第 2 页开始的所有数组到一个维度的单个数组中f_array=np.concatenate((pgno_2,pgno_3,pgno_4,pgno_5,pgno_6,pgno_7),axis=0)#第一次循环赋值这个值如果 array_control_var==0:main_f_array=f_array别的:#问题来了main_f_array=np.array([main_f_array,f_array])array_control_var+=1打印(main_f_array)

当前我的代码生成这样的数组(用于 3 个文件夹)

<块引用><预><代码>[数组([[0,0,0],[0,0,0]]),数组([0,0,0])]

注意:我不知道它有多少维

但是我想要

<块引用><预><代码>[大批([0,0,0][0,0,0][0,0,0])]

解决方案

我尝试编写一个递归代码,将列表列表递归地展平为一个列表.它为您的案例提供了所需的输出,但我没有尝试将其用于许多其他输入(并且在某些情况下它是错误的,例如:list =[0,[[0,0,0],[0,0,0]],[0,0,0]])...

flat = []定义主():列表 =[[[[0,0,0],[0,0,0]],[0,0,0]]recFlat(列表)打印(平面)def recFlat(列表):如果 len(Lists) == 0:返回列表头,尾=列表[0],列表[1:]如果 isinstance(head, (list,)):recFlat(头)返回 recFlat(tail)别的:返回 flat.append(Lists)如果 __name__ == '__main__':主要的()

我在代码背后的想法是遍历每个列表的头部,并检查它是列表还是元素的实例.如果头部是一个元素,这意味着我有一个平面列表,我可以返回该列表.否则,我应该递归遍历更多.

Here, my code feats value form text file; and create matrices as multidimensional array, but the problem is the code create more then two dimensional array, that I can't manipulate, I need two dimensional array, how I do that?

Explain algorithm of my code:

Moto of code: My code fetch value from a specific folder, each folder contain 7 'txt' file, that generate from one user, in this way multiple folder contain multiple data of multiple user.

step1: Start a 1st for loop, and control it using how many folder have in specific folder,and in variable 'path' store the first path of first folder.

step2: Open the path and fetch data of 7 txt file using 2nd for loop.after feats, it close 2nd for loop and execute the rest code.

step3: Concat the data of 7 txt file in one 1d array.

step4(Here the problem arise): Store the 1d arry of each folder as 2d array.end first for loop.

Code:

import numpy as np
from array import *
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=','))")

    #z=np.array([pgno_2,pgno_3,pgno_4,pgno_5,pgno_6,pgno_7])




    #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
    else:
        #here the problem arise 
        main_f_array=np.array([main_f_array,f_array])
    array_control_var+=1
print(main_f_array)

current my code generate array like this(for 3 folder)

[
 array([[0,0,0],[0,0,0]]),
 array([0,0,0])
]

Note: I don't know how many dimension it have

But I want

[
array( 
  [0,0,0]
  [0,0,0]
  [0,0,0])
]

解决方案

I tried to write a recursive code that recursively flattens the list of lists into one list. It gives the desired output for your case, but I did not try it for many other inputs(And it is buggy for certain cases such as :list =[0,[[0,0,0],[0,0,0]],[0,0,0]])...

flat = []

def main():
    list =[[[0,0,0],[0,0,0]],[0,0,0]]
    recFlat(list)
    print(flat)

def recFlat(Lists):
    if len(Lists) == 0:
        return Lists
    head, tail = Lists[0], Lists[1:]
    if isinstance(head, (list,)):
        recFlat(head)
        return  recFlat(tail)
    else:
        return flat.append(Lists)

if __name__ == '__main__':
    main()

My idea behind the code was to traverse the head of each list, and check whether it is an instance of a list or an element. If the head is an element, this means I have a flat list and I can return the list. Else, I should recursively traverse more.

这篇关于如何将多维数组转换为二维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆