Issue
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.
Solution
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
Answered By - Bill the Lizard
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.