This question already has answers here:
Numpy: find index of the elements within range
(12 answers)
How to return indices of values between two numbers in numpy array
(2 answers)
How to conditionally select elements in numpy array
(2 answers)
Closed 1 year ago.
I have the following data lets call it y with the corresponding x values. Plotting plt.plot(x,y) results in: I now want to extract a specific part of that data that is between the x-values of 8.6075 and 8.62. Plotting the part using plt.xlim(8.6075, 8.62) gives the following. I have tried to find the indices using of the x-values using index1=np.where(x==8.6075), index2=np.where(x==8.62) and than just cutting out that specific part of the data using y_cutout = y[index1:index2]. The problem was that the exact values 8.6075 and 9.62 have no indices that they are defined on.
You can find the index of the nearest value by creating a new array of the differences between the values in the original array and the target, then find the index of the minimum value in the new array.
For example, starting with an array of random values in the range 5.0 - 10.0:
import numpy as np
x = np.random.uniform(low=5.0, high=10.0, size=(20,))
print(x)
Find the index of the value closest to 8 using:
target = 8
diff_array = np.absolute(x - target)
print(diff_array)
index = diff_array.argmin()
print(index, x[index])
Output:
[7.74605146 8.31130556 7.39744138 7.98543982 7.63140243 8.0526093
7.36218916 6.62080638 6.18071939 6.54172198 5.76584536 8.69961399
5.83097522 9.93261906 8.21888006 7.63466418 6.9092988 9.2193369
5.41356164 5.93828971]
[0.25394854 0.31130556 0.60255862 0.01456018 0.36859757 0.0526093
0.63781084 1.37919362 1.81928061 1.45827802 2.23415464 0.69961399
2.16902478 1.93261906 0.21888006 0.36533582 1.0907012 1.2193369
2.58643836 2.06171029]
3 7.985439815743841
You can make a selection by following
y_cutout = y[(x >= 8.6075) & (x <= 8.62)]
(Fixed as #AcaNg mentioned in the comment)
Related
This question already has answers here:
Transposing a 1D NumPy array
(15 answers)
numpy's transpose method can't convert 1D row ndarray to a column one [duplicate]
(2 answers)
Numpy transpose of 1D array not giving expected result
(4 answers)
Closed last month.
I know the simple/worked solution to this question is reshape (-1, 1) for turning row vector (numpy.array) into a column vector (numpy.array).
Specifically, I want to understand why numpy.transpose(a) won't work.
Say,
vector_of_1 = np.transpose(np.ones(N)) # statement 1
And if I define a column vector b, and use the following statement:
V = b + vector_of_1
I would get a weird matrix V.
My fix is to use
vector_of_1 = np.ones(N).reshape(-1,1)
And it works as expected (V being a column vector).
But I want to understand why the transpose method (i.e., statement 1) won't work. Detailed explanation is appreciated.
This question already has answers here:
Get the position of the largest value in a multi-dimensional NumPy array
(4 answers)
Closed 3 years ago.
I want to print out the index of an array that has the maximum value (and since indexing begins at 0, I need to add one to the index value to get 1-indexed). Example:
rslt = np.amax(final_array)
print("The maximum value is :", rslt)
print("The optimal choice that has that value is :", rslt.index[])
Context: I am writing some multi-criteria decision analysis code in Python. I import numpy to handle arrays of alternatives, criteria and weights. I use np.amax to find the maximum value in the final array.
use numpy.argmax to find the index of the max value.
import numpy as np
#some list
f = [1,2,3,4,5,6,6,6,6,6]
#max value
print (f"the max value is : { np.amax(f)}")
#indices where max values are located
max_indices = np.argwhere( f == np.amax(f))
#adding 1 to get position
max_positions = [i+1 for i in max_indices.flatten().tolist()]
print(f"Max values are located at : {max_positions}")
#first max value
print(f"First max value occurs at : {max_positions[0]}")
This question already has answers here:
How to normalize a NumPy array to within a certain range?
(8 answers)
Closed 3 years ago.
I am trying to scale a pandas or numpy array from 0 to a unknown max value with the defined number replaced with 1.
One solution I tried is just dividing the defined number I want by the array.
test = df['Temp'] / 33
This method does not scale all the way from 0 and I'm stuck trying to figure out a better mathematical way of solving this.
First, transform the DataFrame to a numpy array
import numpy as np
T = np.array(df['Temp'])
Then scale it to a [0, 1] interval:
def scale(A):
return (A-np.min(A))/(np.max(A) - np.min(A))
T_scaled = scale(T)
Then transform it to anywhere you want, e.g. to [55..100]
T2 = 55 + 45*T_scaled
I'm sure that this can be done within Pandas too (but I'm not familiar with it). Perhaps you might study Pandas df.apply()
scaled = (df['Temp']-df['Temp'].min()) / (33 - df['Temp'].min())
Just replace 33 with the number to want your data scaled to!
This question already has answers here:
Counting the number of non-NaN elements in a numpy ndarray in Python
(5 answers)
Closed 4 years ago.
I'm currently trying to learn Python and Numpy. The task is to determine the length of individual columns of an imported CSV file.
So far I have:
import numpy as np
data = np.loadtxt("assignment5_data.csv", delimiter = ',')
print (data.shape[:])
Which returns:
(62, 2)
Is there a way to iterate through each column to count [not is.nan]?
If I understand correctly, and you are trying to get the length of non-nan values in each column, use:
np.sum(~np.isnan(data),axis=0)
This question already has answers here:
Numpy array of multiple indices replace with a different matrix
(2 answers)
Closed 5 years ago.
If I have:
x = np.asarray([[1,2],[3,4],[5,6]])
And I would like to create:
y = np.asarray([1,4,5])
In order to do this, I built an array as follows:
inds = np.asarray([[0,0],[1,1],[2,0]])
And I passed it to x as follows:
y = x[inds]
This does not yield the elements indexed by the rows in inds. How do I achieve this functionality in either this fashion, or a fashion very similar to this?
This is what advanced indexing for; Extract the row index and column index into two separate arrays and use them to subset the array:
x[inds[:,0], inds[:,1]]
# array([1, 4, 5])