【发布时间】:2016-11-23 19:52:00
【问题描述】:
我有一个模拟模型,它集成了一组变量,这些变量的状态由任意维数的 numpy 数组表示。模拟之后,我现在有一个数组列表,其中的元素表示特定时间点的变量状态。
为了输出模拟结果,我想将这些数组拆分为多个 1D 数组,其中元素对应于状态变量的相同分量随着时间的推移。以下是多个时间步长上的二维状态变量的示例。
import numpy as np
# Arbitrary state that is constant
arr = np.arange(9).reshape((3, 3))
# State variable through 3 time steps
state = [arr.copy() for _ in range(3)]
# Stack the arrays up to 3d. Axis could be rolled here if it makes it easier.
stacked = np.stack(state)
我需要得到的输出是:
[np.array([0, 0, 0]), np.array([1, 1, 1]), np.array([2, 2, 2]), ...]
我尝试过np.split(stacked, sum(stacked.shape[:-1]), axis=...)(尝试了axis= 的所有操作)但收到以下错误:ValueError: array split does not result in an equal division。有没有办法使用np.split 或np.nditer 来做到这一点,这将适用于一般情况?
我猜这相当于做:
I, J, K = stacked.shape
result = []
for i in range(I):
for j in range(J):
result.append(stacked[i, j, :])
这也是我希望得到的订单。很简单,但是我希望 numpy 中有一些我可以利用的更通用的东西。
【问题讨论】: