如何找到数据行中每行值保持不变的第一个连续次数

时间:2019-06-07 08:08:53

标签: python pandas numpy dataframe

如何找到数据行中每行值保持不变的第一个连续计数?

我问了一个与此主题有关的问题;

how to find number of consecutive decreases(increases)

但是我现在有一个稍微不同的问题。我需要找到数据行中每行值保持不变的第一个连续的次数。如果[i]!= [i + 1]的结果必须为0。我尝试了多种解决方案,但遇到一个错误,我将在下面进行解释。

我有一个数据框,其中包含500K行和12列(用于月份),包括开始和结束月份。每列代表一个月。我需要比较范围(startMonth,endmonth)中的第i个月和第(i + 1)个月的每一行。 (注:范围不是恒定的。每行的范围大小都不同。)

条件:如果开始月>结束月,我应该看到“ Neg99 = -999”

这是我的示例数据:

import pandas as pd
import numpy as np

idx = [1001,1002,1003,1004,1005,1006,1007,1008,1009,1010,1011,1012,1013]
data = {'M_1': [3, 1, 0, 0, 1, 0, 1, 1, 1, 0, 6, 6, 6],
        'M_2': [2, 2, 3, 1, 1, 0, 1, 2, 0, 1, 5, 5, 5],
        'M_3': [1, 3, 2, 2, 1, 0, 1, 2, 1, 0, 4, 4, 4],
        'M_4': [0, 4, 1, 3, 1, 0, 1, 2, 0, 1, 3, 0, 3],
        'M_5': [1, 0, 0, 4, 2, 0, 1, 3, 1, 0, 2, 1, 2],
        'M_6': [2, 0, 0, 0, 3, 0, 1, 3, 0, 1, 1, 2, 1],
        'M_7': [3, 0, 0, 0, 2, 0, 1, 2, 1, 0, 0, 3, 0],
        'M_8': [0, 1, 0, 0, 2, 0, 1, 2, 0, 1, 1, 1, 1],
        'M_9': [0, 2, 0, 0, 1, 0, 1, 2, 1, 0, 0, 0, 0],
        'M_10': [0, 3, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0],
        'M_11': [0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0],
        'M_12': [0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0]}

startMonth = pd.DataFrame([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 4, 4, 5],
                          columns=['start'],index=idx)
endMonth = pd.DataFrame([12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 2],
                        columns=['end'], index=idx)

df1 = pd.DataFrame(data, index=idx)
Neg99 = -999

我写了日期范围的布尔数组;

arr_bool = (np.less_equal.outer(startMonth.start, range(1,13)) 
            & np.greater_equal.outer(endMonth.end, range(1,13))
            )

masked=df1.filter(regex='M_[0-9]').mask(~arr_bool)

我尝试过了

eql = (np.diff(np.hstack((masked.values, np.zeros((masked.values.shape[0], 1)))), axis=1) == 0).argmin(axis=1)

final_eql = pd.DataFrame(eql,
                      index=idx, columns=['eql'])
final_eql.eql= np.select( condlist = [startMonth.start > endMonth.end],
                           choicelist = [Neg99],
                           default = final_eql.eql)

但是对于idx = 1006(所有值都等于零),我无法获得所需的结果。

我想得到这些结果: 预期输出:

1001    0
1002    0
1003    0
1004    0
1005    3
1006    11
1007    11
1008    0
1009    0
1010    0
1011    0
1012    0
1013    -999

但是我得到了以下结果:

1001    0
1002    0
1003    0
1004    0
1005    3
1006    0
1007    11
1008    0
1009    0
1010    0
1011    0
1012    0
1013    -999

0 个答案:

没有答案