My starting point is a pandas data frame which I convert into a numpy array:
我的出发点是一个pandas数据框,我将其转换为numpy数组:
> df = pd.DataFrame({"a":[1,2,3,4],"b":[4,5,6,7],"c":[7,8,9,10]})
> arr = df.as_matrix()
The array is now 2-dimensional of shape (4,3):
该阵列现在是二维形状(4,3):
> arr
array([[ 1, 4, 7],
[ 2, 5, 8],
[ 3, 6, 9],
[ 4, 7, 10]])
What I would like to do is to convert arr
into its 4-dimensional and (4,3,1,1) shaped equivalent by effectively mapping every singular element like f.x. 5
onto [[5]]
.
我想做的是通过有效地映射每个奇异元素,如f.x,将arr转换为其4维和(4,3,1,1)形状的等价物。 5到[[5]]。
The new arr
would be:
新的arr将是:
array([[ [[1]], [[4]], [[7]] ],
[ [[2]], [[5]], [[8]] ],
[ [[3]], [[6]], [[9]] ],
[ [[4]], [[7]], [[10]] ]])
How would I do that elegantly and fast?
我怎么能优雅而快速地做到这一点?
1 个解决方案
#1
Do arr[:, :, None, None]
to add two extra axes. Here is an example:
arr [:,:,None,None]添加两个额外的轴。这是一个例子:
In [5]: arr[:, :, None, None].shape
Out[5]: (4, 3, 1, 1)
None
in indexing is a synonym for np.newaxis
, which selects data and adds a new axis. Many people would prefer to write the above as
索引中的无是np.newaxis的同义词,它选择数据并添加新轴。很多人宁愿把上面的内容写成
arr[:, :, np.newaxis, np.newaxis]
arr [:,:,np.newaxis,np.newaxis]
for legibility reasons
出于易读的原因
#1
Do arr[:, :, None, None]
to add two extra axes. Here is an example:
arr [:,:,None,None]添加两个额外的轴。这是一个例子:
In [5]: arr[:, :, None, None].shape
Out[5]: (4, 3, 1, 1)
None
in indexing is a synonym for np.newaxis
, which selects data and adds a new axis. Many people would prefer to write the above as
索引中的无是np.newaxis的同义词,它选择数据并添加新轴。很多人宁愿把上面的内容写成
arr[:, :, np.newaxis, np.newaxis]
arr [:,:,np.newaxis,np.newaxis]
for legibility reasons
出于易读的原因