I have a pandas Series and I have performed cumsum()
on it. The resulting Series looks like:
A = [10, 25, 30, 20, 27, 29]
I want to find the range in the series in which a certain value lies.
For example, the value 28 lies between (25, 30), (30, 20) and (27,29). In this case I want to find either the last or all such ranges. How can I achieve this natively in pandas and without extra loops?
Here a possible numpy approach:
import numpy as np
a = np.array([10, 25, 30, 20, 27, 29])
v = 28 # value to find
# Define intervals
intervals = {i: f'[ {min(i1, i2)}, {max(i1,i2)} ]' for i, (i1,i2) in enumerate(zip(a[:-1],a[1:]))}
intervals
{0: '[ 10, 25 ]', 1: '[ 25, 30 ]', 2: '[ 20, 30 ]', 3: '[ 20, 27 ]', 4: '[ 27, 29]'}
# Find indices of intervals
b = a-v
indices = np.squeeze(np.argwhere(b[:-1] *b[1:]<=0))
indices
array([1, 2, 4], dtype=int64)
[intervals[i] for i in indices]
['[ 25, 30 ]', '[ 20, 30 ]', '[ 27, 29 ]']
Does this answer your question?
A = [10, 25, 30, 20, 27, 29]
def tuple_finder(num_value, num_array):
i = 0
j = i + 1
tuple_list = []
for e in num_array[:-1]:
if (num_array[i] <= num_value <= num_array[j])\
or (num_array[i] >= num_value >= num_array[j]):
print(num_array[i], num_array[j])
tuple_list.append((num_array[i], num_array[j]))
i += 1
j += 1
else:
i += 1
j += 1
print(tuple_list[-1])
tuple_finder(28, A)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.