Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Take a numpy view with singleton dimension

Tags:

python

numpy

Setup

I have a Fortran ordered numpy array with a singleton first dimension

In [1]: import numpy as np

In [2]: x = np.array([[1, 2, 3]], order='F')

In [3]: x.strides
Out[3]: (8, 8)

I take a view of this array with a dtype with a smaller size

In [4]: y = x.view('i2')

In [5]: y
Out[5]: array([[1, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0]], dtype=int16)

In [6]: y.strides
Out[6]: (8, 2)

Questions

First, should I be concerned by that strides result? There are more than eight bytes to the next row.

Second, I really wanted this array's shape to be (4, 3), not (12, 3). Normally with Fortran laid out arrays .view will expand the first dimension, not the second.

Third, how do I turn the array above (or any array produced by a similar process, into a (4, 3) array such that, in this case, three out of four rows are all zeros. Am I missing a clever transposition trick?

Versions

In [3]: sys.version_info
Out[3]: sys.version_info(major=3, minor=4, micro=3, releaselevel='final', serial=0)

In [4]: numpy.__version__
Out[4]: '1.10.1'
like image 866
MRocklin Avatar asked Nov 10 '22 01:11

MRocklin


1 Answers

Curiously, when I repeat your steps I get the (4,3) right away:

In [637]: x=np.array([[1,2,3]],'int64',order='F')
In [638]: x
Out[638]: array([[1, 2, 3]], dtype=int64)
In [639]: y=x.view('i2')
In [640]: y
Out[640]: 
array([[1, 2, 3],
       [0, 0, 0],
       [0, 0, 0],
       [0, 0, 0]], dtype=int16)
In [641]: x.shape
Out[641]: (1, 3)
In [642]: y.shape
Out[642]: (4, 3)
In [643]: x.strides
Out[643]: (8, 8)
In [644]: y.strides
Out[644]: (2, 8)

My numpy 1.8.2 on Py3 (old 32b machine)

With order C

In [655]: x=np.array([[1,2,3]],'int64')
In [656]: y=x.view('i2')
In [657]: y
Out[657]: array([[1, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0]], dtype=int16)
In [658]: y.strides
Out[658]: (24, 2)
In [659]: x.strides
Out[659]: (24, 8)
like image 112
hpaulj Avatar answered Nov 15 '22 07:11

hpaulj