簡體   English   中英

顯示數字是否在 pandas 中最多 3 個位置是連續的

[英]display if the numbers are consecutive for upto 3 positions exactly in pandas

我有一個 df“Index_label”,它只有一個包含數字的列(名稱:column1)。

如果我們有連續的 position ==3。 我想要它作為輸出

第 1 列

25

26------------連續最多2個位置

110

111

112

113---------------------連續最多4個位置

455

456

457---------連續最多3個位置

所需的o / p:

110

111

112

455

456

457

您可以使用此代碼(假設您將數字作為某種迭代):

def getConsecutive(numbers):
  consecutive = []                                 # all 3-consecutive numbers
  sub_series = []                                  # current sub-series of consecutive numbers

  for number in numbers:

    if len(sub_series) == 0:                       # if the current sub-series is empty
      sub_series.append(number)                    # add the current number to it
    else:
      prev = sub_series[-1]         
      if number != prev+1:                         # if the current number is not consecutive
        if len(sub_series) >=3:                    # if there are at least 3 numbers in the sub_series
           consecutive.extend(sub_series[0:3])     # add the first 3 of the sub-series
        sub_series.clear()                         # clear the sub-series
      sub_series.append(number)                    # add the current number 

  if len(sub_series) >=3:                          # check if a 3-consecutive sub series is found
    consecutive.extend(sub_series[0:3])            # add it in

  return consecutive


numbers1 = [25,26,110,111,112,113,455,456,457]
numbers2 = [110, 111, 112, 113, 114, 115, 116, 117]
print(getConsecutive(numbers1))         # output = [110, 111, 112, 455, 456, 457]
print(getConsecutive(numbers2))         # output = [110, 111, 112]

這有效(我認為?),使用while循環並在找到連續系列時增加計數:

def three_in_a_row(array):
    output=[]
    c = 0  
    while c < len(array)-2: 
        if (array[c] + 1 == array[c+1]) and (array[c] + 2 == array[c+2]): 
            output += [array[c],array[c+1],array[c+2]] 
            d = 1
            while (array[c] + d == array[c+d]):
                d+=1
                if (d+c) >= len(array):
                    break
            c += d
        else:
            c+=1
    return output

print(three_in_a_row([1,2,3,4,5,6,7,8,9]))
print(three_in_a_row([1,2,3,7,8,9]))
print(three_in_a_row([1,8,9,4,2,4,5,6,7,8]))

Output:

[1, 2, 3]
[1, 2, 3, 7, 8, 9]
[4, 5, 6]

有趣的運動!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM