【问题标题】:How to find a value in a cumulative pandas Series?如何在累积的熊猫系列中找到一个值?
【发布时间】:2020-08-02 04:56:39
【问题描述】:

我有一个熊猫系列,我在上面表演了cumsum()。生成的 Series 如下所示:

A = [10, 25, 30, 20, 27, 29]

我想在序列中找到某个值所在的范围。

例如,值 28 介于 (25, 30)、(30, 20) 和 (27,29) 之间。在这种情况下,我想找到最后一个或所有这样的范围。我怎样才能在 pandas 中实现这一点而无需额外的循环?

【问题讨论】:

    标签: python pandas data-science data-analysis


    【解决方案1】:

    这是一种可能的 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 ]']
    

    【讨论】:

      【解决方案2】:

      这能回答你的问题吗?

      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)
      

      【讨论】:

      • 虽然它确实解决了问题,但我正在寻找一种使用 pandas 方法且不使用循环来实现此目的的方法。
      猜你喜欢
      • 2022-06-10
      • 1970-01-01
      • 2019-01-23
      • 2014-01-14
      • 1970-01-01
      • 2021-04-10
      • 2017-05-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多