[英]How to find a value in a cumulative pandas Series?
我有一个 pandas 系列,我已经对其执行了cumsum()
。 结果系列看起来像:
A = [10, 25, 30, 20, 27, 29]
我想找到某个值所在的系列中的范围。
例如,值 28 介于 (25, 30)、(30, 20) 和 (27,29) 之间。 在这种情况下,我想找到最后一个或所有这样的范围。 如何在 pandas 中本地实现这一点并且没有额外的循环?
这是一种可能的 numpy 方法:
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 ]']
这回答了你的问题了吗?
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.