[英]How to concatenate 2D arrays on the fly in Python?
I am trying to concatenate 2D arrays horizontally using numpy in a dynamic way.我正在尝试以动态方式使用 numpy 水平连接二维数组。 Starting from an empty array I want to add 2D arrays depending on the if condition outcome.
从一个空数组开始,我想根据 if 条件结果添加二维数组。 I don't know the final dimension so I cannot define anything before the loop starts.
我不知道最终的维度,所以在循环开始之前我无法定义任何东西。 Assuming I have the 2D arrays called A,B,C:
假设我有名为 A、B、C 的二维数组:
X = np.array([])
for name in modules:
if name = 'AAA':
X = np.append(X,A, axis = 1)
if name = 'BBB'
X = np.append(X,B, axis = 1)
if name = 'CCC'
X = np.append(X,C, axis = 1)
After reading how np.append works I realized why this solution is wrong.在阅读 np.append 如何工作后,我意识到为什么这个解决方案是错误的。 Is there an easy way to produce concatenation on the fly?
有没有一种简单的方法可以即时生成连接? N:B: I know the number of columns and rows of A,B,C (they have the same number of rows) but I cannot know how many matrices will be concatenated since all is depending on the if conditions.
N:B:我知道 A、B、C 的列数和行数(它们具有相同的行数)但我不知道将连接多少个矩阵,因为一切都取决于 if 条件。 The concatenation order is important and should be as reported in the code.
连接顺序很重要,应该在代码中报告。
You could create a dictionary which functions as a lookup-table, matching the names with the arrays.您可以创建一个用作查找表的字典,将名称与数组匹配。
mapper = {'AAA': A,
'BBB': B,
'CCC': C}
X = np.hstack([mapper[name] for name in modules])
Because at first, X
does not have the same number of rows as A
, B
or C
, you can not append X
with any of them.因为一开始,
X
的行数与A
、 B
或C
的行数不同,所以您不能将X
附加到其中任何一个。 Here is a small tweak:这是一个小调整:
X = None
for name in modules:
if name = 'AAA':
X = np.append(X,A, axis = 1) if X is not None else A
if name = 'BBB'
X = np.append(X,B, axis = 1) if X is not None else B
if name = 'CCC'
X = np.append(X,C, axis = 1) if X is not None else C
Hope this would be helpful.希望这会有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.