Shirink the numpy array with max - python

I have numpy array such as np.array([2,2])
[[1,9],
[7,3]]
I want to get the max of third demention and make this into one dimension.
then numpy.array should be like this [9,7]
I think I can do this with for loop and make another numpy.
However it looks ackword, is there any good way to do this ?

amax function (alias is np.max)
import numpy as np
a = np.array([[1,9],
[7,3]])
np.amax(a, axis=1)
# array([9, 7])

Use max with specific axis. In this example axis is 1.
import numpy as np
arr = np.array([[1,9],
[7,3]])
arr_max = np.max(arr, axis=1)
print(arr_max)
Output:
[9 7]

numpy.max is just an alias for numpy.amax. This function only works on a single input array and finds the value of maximum element in that entire array (returning a scalar). Alternatively, it takes an axis argument and will find the maximum value along an axis of the input array (returning a new array).
import numpy
np_array = numpy.array([[1,9],
[7,3]])
max_array = numpy.max(np_array, axis=1)
print(max_array.shape)
print(max_array)
Output:
(2,)
[9 7]

Related

Numpy array reshape customization python

I have an np array n and the shape is (250,250). after that I converted (final array w)it into (250,250,3) because I need to do some operation on it.
is it possible to convert the shape of w to (250,250)?
thanks in advance.
I tried some reshaping operation of Numpy but it does not work!
Numpy reshaping array
Comparing two NumPy arrays for equality, element-wise
Numpy reshaping array
numpy.reshape
Gives a new shape to an array without changing its data.
so this is not right to convert array with shape of (250,250,3) into array with shape of (250,250) as 1st does have 187500 cells and 2nd does have 62500 cells.
You probably should use slicing, consider following example
import numpy as np
arr = np.array([[[0,1],[2,3]],[[4,5],[6,7]]]) # has shape (2,2,2)
arr2 = arr[:,:,0] # get certain cross-section, check what will happend if you use 1 inplace of 0 and 2 inplace of 0
print("arr2")
print(arr2)
print("arr2.shape",arr2.shape)
output
arr2
[[0 2]
[4 6]]
arr2.shape (2, 2)

Python: Broadcast 2D index array from argmin in a 3D array

I have a 3D grid with different values, and apply argmin along axis=2 to it, to get the lowest value in third dimension. How can I now extract the actual value and not only the index of the minimum value?
import numpy as np
input = np.random.normal(size=(30,40,10))
minvals = np.argmin(input,axis=2)
foo = input[minvals]
Minvals give my the index along axis 2 for the minimum value as expected. I expected, that foo gives my a 2D array with the actual minimum values, but foo is now a 4D array...
Try take_along_axis mixed with expand_dims. See the take_along_axis tutorial for more details:
import numpy as np
input = np.random.normal(size=(30,40,10))
minvals = np.argmin(input,axis=2)
foo = np.take_along_axis(input, np.expand_dims(minvals, axis=2), axis=2).reshape(30,40)
# Verification
foo_2 = np.min(input,axis=2)
print('Good result!' if np.allclose(foo,foo_2) else 'Bad results')
Ouput:
% python3 script.py
Good result!

matplotlib: How to conditionally plot a histogram from a 2d array

I have a 2D array, where I am trying to plot a histogram of all the rows in one column, given a condition in another column. I am trying to select subdata in the plt.hist() command, to avoid making numerous subarrays, which I already know how to do. For example if
a_long_named_array = [1, 5]
[2, 6]
[3, 7]
I could create a subset of my array such that the 1st column is greater than 5 by writing
a_long_named_subarray = a_long_named_array[a_long_named_array[:,1] > 5]
How do I plot this subdata without making the aforementioned subarray? Please see below.
import numpy as np
import matplotlib.pyplot as plt
#Generate 2D array
arr = np.array([np.random.random_integers(0,10, 10), np.arange(0,10)])
#Transpose it
arr = arr.T
#----------------------------------------------------------------------------
#Plotting a Histogram: This works
#----------------------------------------------------------------------------
#Plot all the rows of the 0'th column
plt.hist(arr[:,0])
plt.show()
#----------------------------------------------------------------------------
#Plotting a conditional Histogram: This is what I am trying to do. This Doesn't work.
#----------------------------------------------------------------------------
#Plot all the rows of the 0th column where the 1st column is some condition (here > 5)
plt.hist(arr[:,0, where 1 > 5])
plt.show()
quit()
You just need to apply the boolean index (whatever > 5 returns a boolean array) to the first dimension.
You're currently trying to index the array along the third dimension with the boolean mask. The array is only 2D, so you're probably getting an IndexError. (Most likely "IndexError: too many indices".)
For example:
import numpy as np
# Your example data
arr = np.array([np.random.random_integers(0,10, 10), np.arange(0,10)])
arr = arr.T
# What you want:
print arr[arr[:,1] > 5, 0]
Basically, in place of the :, you just put in the boolean mask (something > 5). You might find it clearer to write:
mask = arr[:,1] > 5
result = arr[mask, 0]
Another way of thinking of this is:
second_column = arr[:,1]
first_column = arr[:,0]
print first_column[second_column > 5]

Index the middle of a numpy array?

To index the middle points of a numpy array, you can do this:
x = np.arange(10)
middle = x[len(x)/4:len(x)*3/4]
Is there a shorthand for indexing the middle of the array? e.g., the n or 2n elements closes to len(x)/2? Is there a nice n-dimensional version of this?
as cge said, the simplest way is by turning it into a lambda function, like so:
x = np.arange(10)
middle = lambda x: x[len(x)/4:len(x)*3/4]
or the n-dimensional way is:
middle = lambda x: x[[slice(np.floor(d/4.),np.ceil(3*d/4.)) for d in x.shape]]
Late, but for everyone else running into this issue:
A much smoother way is to use numpy's take or put.
To address the middle of an array you can use put to index an n-dimensional array with a single index. Same for getting values from an array with take
Assuming your array has an odd number of elements, the middle of the array will be at half of it's size. By using an integer division (// instead of /) you won't get any problems here.
import numpy as np
arr = np.array([[0, 1, 2],
[3, 4, 5],
[6, 7, 8]])
# put a value to the center
np.put(arr, arr.size // 2, 999)
print(arr)
# take a value from the center
center = np.take(arr, arr.size // 2)
print(center)

Convert a 1D array to a 2D array in numpy

I want to convert a 1-dimensional array into a 2-dimensional array by specifying the number of columns in the 2D array. Something that would work like this:
> import numpy as np
> A = np.array([1,2,3,4,5,6])
> B = vec2matrix(A,ncol=2)
> B
array([[1, 2],
[3, 4],
[5, 6]])
Does numpy have a function that works like my made-up function "vec2matrix"? (I understand that you can index a 1D array like a 2D array, but that isn't an option in the code I have - I need to make this conversion.)
You want to reshape the array.
B = np.reshape(A, (-1, 2))
where -1 infers the size of the new dimension from the size of the input array.
You have two options:
If you no longer want the original shape, the easiest is just to assign a new shape to the array
a.shape = (a.size//ncols, ncols)
You can switch the a.size//ncols by -1 to compute the proper shape automatically. Make sure that a.shape[0]*a.shape[1]=a.size, else you'll run into some problem.
You can get a new array with the np.reshape function, that works mostly like the version presented above
new = np.reshape(a, (-1, ncols))
When it's possible, new will be just a view of the initial array a, meaning that the data are shared. In some cases, though, new array will be acopy instead. Note that np.reshape also accepts an optional keyword order that lets you switch from row-major C order to column-major Fortran order. np.reshape is the function version of the a.reshape method.
If you can't respect the requirement a.shape[0]*a.shape[1]=a.size, you're stuck with having to create a new array. You can use the np.resize function and mixing it with np.reshape, such as
>>> a =np.arange(9)
>>> np.resize(a, 10).reshape(5,2)
Try something like:
B = np.reshape(A,(-1,ncols))
You'll need to make sure that you can divide the number of elements in your array by ncols though. You can also play with the order in which the numbers are pulled into B using the order keyword.
If your sole purpose is to convert a 1d array X to a 2d array just do:
X = np.reshape(X,(1, X.size))
convert a 1-dimensional array into a 2-dimensional array by adding new axis.
a=np.array([10,20,30,40,50,60])
b=a[:,np.newaxis]--it will convert it to two dimension.
There is a simple way as well, we can use the reshape function in a different way:
A_reshape = A.reshape(No_of_rows, No_of_columns)
You can useflatten() from the numpy package.
import numpy as np
a = np.array([[1, 2],
[3, 4],
[5, 6]])
a_flat = a.flatten()
print(f"original array: {a} \nflattened array = {a_flat}")
Output:
original array: [[1 2]
[3 4]
[5 6]]
flattened array = [1 2 3 4 5 6]
some_array.shape = (1,)+some_array.shape
or get a new one
another_array = numpy.reshape(some_array, (1,)+some_array.shape)
This will make dimensions +1, equals to adding a bracket on the outermost
Change 1D array into 2D array without using Numpy.
l = [i for i in range(1,21)]
part = 3
new = []
start, end = 0, part
while end <= len(l):
temp = []
for i in range(start, end):
temp.append(l[i])
new.append(temp)
start += part
end += part
print("new values: ", new)
# for uneven cases
temp = []
while start < len(l):
temp.append(l[start])
start += 1
new.append(temp)
print("new values for uneven cases: ", new)
import numpy as np
array = np.arange(8)
print("Original array : \n", array)
array = np.arange(8).reshape(2, 4)
print("New array : \n", array)

Categories

Resources