Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

retain dimensions for numpy slice

19 views
Skip to first unread message

duncan smith

unread,
Oct 24, 2016, 1:37:09 PM10/24/16
to
Hello,
I have several arrays that I need to combine elementwise in
various fashions. They are basically probability tables and there is a
mapping of axes to variables. I have code for transposing and reshaping
that aligns the variables / axes so the usual broadcasting rules achieve
the desired objective. But for a specific application I want to avoid
the transposing and reshaping. So I've specified arrays that contain the
full dimensionality (dimensions equal to the total number of variables).
e.g.

Arrays with shape,

[1,3,3] and [2,3,1]

to represent probability tables with variables

[B,C] and [A,B].

One operation that I need that is not elementwise is summing over axes,
but I can use numpy.sum with keepdims=True to retain the appropriate shape.

The problem I have is with slicing. This drops dimensions. Does anyone
know of a solution to this so that I can e.g. take an array with shape
[2,3,1] and generate a slice with shape [2,1,1]? I'm hoping to avoid
having to manually reshape it. Thanks.

Duncan

Peter Otten

unread,
Oct 24, 2016, 2:06:30 PM10/24/16
to
Can you clarify your requirement or give an example of what you want?

Given an array

>>> a.shape
(2, 3, 1)

you can get a slice with shape (2,1,1) with (for example)

>>> a[:,:1,:].shape
(2, 1, 1)

or even

>>> newshape = (2, 1, 1)
>>> a[tuple(slice(d) for d in newshape)].shape
(2, 1, 1)

but that's probably not what you are asking for...

duncan smith

unread,
Oct 24, 2016, 7:39:16 PM10/24/16
to
Thanks. I think that's exactly what I wanted.

Duncan
0 new messages