I have a numpy array with shape (3,10,10).
How can I change the array such that the first coordinate (column) will be the last, and the last will be the first (e.g. the shape of the array will be (10, 10, 3))?
I tried:
arr.flatten().reshape((10,10,3))
Is there a more elegant/efficient way?
You should use transpose function with axes parameter:
>>>import numpy as np
>>>x = np.ones((3,10,10))
>>>tx = np.transpose(x, (2, 1, 0))
>>>tx.shape
(10, 10, 3)
Related
I have essentially a 2D grid of N by M (i.e. N rows, and M columns). I would like to sample from this grid without replacement in Cython without requiring the GIL. I would want something like this
for j in range(n_samples):
row_idx, col_idx = sample_without_replacement(grid)
So for example, say my 2D grid is 3 x 4, then I might get the following samples
(0, 3),
(0, 2),
(2, 1),
(3, 0)
Is there a simple way to do this in Cython?
I want to create a pcolormesh plot with a discrete logarithmic colorbar. Some resolution is lost, but the matching between colors and values seems to be easier (at least for me) if the colormap is discrete.
The code snippet below produces a continuous log colormap with the preferred value range. How can I make it discrete? Here I found how to create a discrete linear colormap, but I couldn't extend it to log scale.
plt.pcolormesh(X,Y,Z,norm=mcolors.LogNorm(vmin=0.01, vmax=100.))
plt.colorbar()
fig = matplotlib.pyplot.gcf()
fig.set_size_inches(4*2.5, 3*2.5)
plt.xlabel("X", horizontalalignment='right', x=1.0)
plt.ylabel("Y", horizontalalignment='right', y=1.0)
plt.tight_layout()
I've managed to create a logarithmic colorbar with even spacing. However, I couldn't figure out how to create a discrete logarithmic colorbar with a logarithmic spacing of the colorbar. I hope this helps!
import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np
X = np.arange(0, 50)
Y = np.arange(0, 50)
Z = np.random.rand(50, 50)*10
bounds = [0, 0.1, 0.2, 0.3, 0.4, 0.5, .7, .8, .9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
num_c = len(bounds)
cmap = mpl.colormaps['viridis'].resampled(num_c)
norm = mpl.colors.BoundaryNorm(bounds, cmap.N)
fig, ax = plt.subplots()
fig.set_size_inches(4*2.5, 3*2.5)
ax.pcolormesh(X, Y, Z, norm=norm, cmap=cmap)
plt.xlabel("X", horizontalalignment='right', x=1.0)
plt.ylabel("Y", horizontalalignment='right', y=1.0)
fig.colorbar(mpl.cm.ScalarMappable(cmap=cmap, norm=norm))
plt.tight_layout()
I assume this is possible. Example: I have polygons in a geodataframe, some polygons have the same attribute data, they are just separate individual polygons with the same data, each polygon has its own row in the gdf.
I would like to combine the polygons into a multipolygon so they take up only 1 row in the gdf.
The two polygons overlap, I do not want to dissolve them together, I want them to remain 2 separate entities.
There are single polygons, I assume they will also have to be converted to multipolygons even though they are in the singular as ultimately they will be exported for use in GIS software, one geom type per dataset.
I have achieved a .dissolve(by='ID') but as stated above, I do not want to change the polygons geometry.
Suggestions?
You can adapt geopandas' dissolve to generate MultiPolygon instead of unary union. The original code I adapted is here.
import geopandas as gpd
from shapely.geometry import Polygon, MultiPolygon
def groupby_multipoly(df, by, aggfunc="first"):
data = df.drop(labels=df.geometry.name, axis=1)
aggregated_data = data.groupby(by=by).agg(aggfunc)
# Process spatial component
def merge_geometries(block):
return MultiPolygon(block.values)
g = df.groupby(by=by, group_keys=False)[df.geometry.name].agg(
merge_geometries
)
# Aggregate
aggregated_geometry = gpd.GeoDataFrame(g, geometry=df.geometry.name, crs=df.crs)
# Recombine
aggregated = aggregated_geometry.join(aggregated_data)
return aggregated
df = gpd.GeoDataFrame(
{"a": [0, 0, 1], "b": [1, 2, 3]},
geometry=[
Polygon([(0, 0), (1, 0), (1, 1)]),
Polygon([(1, 0), (1, 0), (1, 1)]),
Polygon([(0, 2), (1, 0), (1, 1)]),
],
)
grouped = groupby_multipoly(df, by='a')
grouped
geometry b
a
0 MULTIPOLYGON (((0.00000 0.00000, 1.00000 0.000... 1
1 MULTIPOLYGON (((0.00000 2.00000, 1.00000 0.000... 3
If you change MultiPolygon within merge_geometries to GeometryCollection, you should be able to combine any type of geometry to a single row. But that might not be supported by certain file formats.
I have a list of coordinates a = [(1,2),(1,300),(2,3).....]
These values area coordinates of 1000 x 1000 NumPy array.
Let's say I want to sum all the values under these coordinates. Is there a faster way to do it than:
sum([array[i[0],i[1]] for i in a])
Apply a mask to array using a and then sum over the masked array. Example:
# Prepare sample array and indices
a = np.arange(10*10).reshape(10,10)
ind = [(1,0), (2, 4), (2,6), (7,7), (8,9), (9,3)]
# Cast list of coordinates into a form that will work for indexing
indx = np.split(np.array(ind), 2, axis = 1)
# A warning may be raised about not using tuples for indexing. You can use tuple(indx) to avoid that.
np.sum(a[indx])
I have a directory of images for a CNN. I would like to be able to rearrange each band in a different order to help better train my model to allow it to recognize my objects. I so far have some code working with cv2. It is separating the bands, but I am having trouble rearranging the bands.
import cv2
import numpy
img = cv2.imread("IMG_4540.jpg")
g,b,r = cv2.split(img)
cv2.imwrite('green_channel.jpg', g)
I would like to have 6 separate images all with different band combinations from one singular image if possible.
You can just form all reorderings with numpy's indexing capabilities.
import numpy as np
from itertools import permutations
# first generate all sets of rearrangements you'd like to make..
orderings = [p for p in permutations(np.arange(3)) if p!=(0,1,2)]
# [(0, 2, 1), (1, 0, 2), (1, 2, 0), (2, 0, 1), (2, 1, 0)]
# rbg, brg, and so on.
# then reorder along axis=-1 using these. (0,1,2) --> (0,2,1) and so on.
for order in orderings:
reordered = im[...,order]
# then save each an appropriate filename
cv2.imsave('filename.jpg', reordered)
del reordered, order