简体   繁体   English

从2D矩阵生成器创建3D矩阵

[英]Create a 3D matrix from a generator of 2D matrices

I am using pandas to read a number of .csv files. 我正在使用pandas读取许多.csv文件。 Each file will produce a 3x5 dataframe. 每个文件将产生一个3x5数据帧。

dtx = (pd.read_csv(f).values for f in get_filelist(datadirectory))

I want to combine all the data from the various files in order to create a 3 dimensional array (if I have 10 files then I want to end up with an array of shape: 10x3x5 ) 我想合并来自各个文件的所有数据,以创建一个3维数组(如果我有10个文件,那么我想得到一个形状为10x3x5的数组)

I could create an empty python list and append all the arrays found in dtx using a for loop, but I would like a more pythonic solution. 我可以创建一个空的python列表,并使用for循环附加在dtx找到的所有数组,但是我想要一个更多的pythonic解决方案。 I have tried 我努力了

np.concatenate([tf for tf in dtx])

without having the desired effect. 没有理想的效果。 How can I concatenate all of the data I read from my .csv files into a big 3D array? 如何将从.csv文件读取的所有数据连接到一个大型3D阵列中?

You can add a new dimension to the arrays and concatenate them: 您可以向数组添加新维度并将其串联:

dtx = (pd.read_csv(f).values for f in get_filelist(datadirectory))
np.concatenate([tf[np.newaxis] for tf in dtx], axis=0)

Example: 例:

np.concatenate([tf[np.newaxis] for tf in (np.arange(4).reshape((2,2)) for i in range(3))], axis=0)
>> array([[[0, 1],
        [2, 3]],

       [[0, 1],
        [2, 3]],

       [[0, 1],
        [2, 3]]])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM