Reputation: 63
I have been using mplot3d (part of matplotlib) for some various 3d plotting, and it has been performing the job admirably. However, I have run into a new problem.
Mplot3d expects data to be sorted in a certain fashion, to plot a wireframe. For example, it likes something like this:
x = array([[1, 2, 3],
[1, 2, 3],
[1, 2, 3]])
y = array([[1, 1, 1],
[2, 2, 2],
[3, 3, 3])
where z is then an array of the same dimensions, with data corresponding to each of those positions in space.
Unfortunately, my data isn't formatted like this - every other row is reversed, because the data is collected by scanning in a raster pattern.
So I have something more like:
x = array([[1, 2, 3],
[3, 2, 1],
[1, 2, 3]])
My current approach is a very ugly, brute-force "do a for loop then check if you're in an odd row or not" that builds a new array out of the old one, but I am hoping there is a more elegant way of doing this. The tricky part is that I have to re-arrange the Z array in the same way I do the X and Y, to ensure that the data corresponding with each point is space is preserved.
Ideally, I'd like something that's robust and specifically designed to sort a set of 2-d arrays that contain arbitrary random position points, but even a more pythonic way of doing what I'm already doing would be appreciated. If I could make it more robust, and not dependent on this specific raster scanning pattern, it would probably save me headaches in the long term.
Upvotes: 3
Views: 992
Reputation: 284602
If I understand you correctly, you just want to do this: x[1::2, :] = x[1::2, ::-1]
.
There are a few kinks... If you don't make an intermediate copy of x
it doesn't quite do what you'd expect due to the way broadcasting works in numpy.
Nonetheless, it's still pretty simple to do with basic indexing:
import numpy as np
x = np.array([[1,2,3],[3,2,1],[1,2,3],[3,2,1],[1,2,3]])
x_rev = x.copy()
x_rev[1::2, :] = x[1::2, ::-1]
This converts this (x
):
array([[1, 2, 3],
[3, 2, 1],
[1, 2, 3],
[3, 2, 1],
[1, 2, 3]])
Into this (x_rev
):
array([[1, 2, 3],
[1, 2, 3],
[1, 2, 3],
[1, 2, 3],
[1, 2, 3]])
In case you're not familiar with slicing in python, x[1::2]
would select every other item of x
, starting with the second item. (1
is the the start index, 2
is the increment) In contrast, x[::-1]
just specifies an increment of -1
, thus reversing the array. In this case we're only applying these slices to a particular axis, so we can select and reverse every other row, starting with the second row.
Upvotes: 2