比较同一数据框列中的值

时间:2017-03-25 14:28:41

标签: python pandas numpy

有没有比较pandas DataFrame的同一列中的值?

手头的任务是这样的:

import pandas as pd
data = pd.DataFrame({"A": [0,-5,2,3,-3,-4,-4,-2,-1,5,6,7,3,-1]});

我需要找到连续+/-值出现的最大时间(在索引中)(等效地检查连续值,因为符号可以用True / False编码)。上述数据应该产生5,因为有5个连续的负整数[-3,-4,-4,-2,-1]

如果可能的话,我希望避免使用循环,因为列中的数据点数量可能会超过数百万。

我已尝试使用data.A.rolling()及其变种,但似乎无法以矢量化的方式找出任何可能的方法。

有什么建议吗?

1 个答案:

答案 0 :(得分:2)

这是一种NumPy方法,用于计算正值和负值的最大间隔长度 -

def max_interval_lens(arr):
    # Store mask of positive values
    pos_mask = arr>=0

    # Get indices of shifts
    idx = np.r_[0,np.flatnonzero(pos_mask[1:] != pos_mask[:-1])+1, arr.size]

    # Return max of intervals
    lens = np.diff(idx)
    s = int(pos_mask[0])
    maxs = [0,0]    
    if len(lens)==1:
        maxs[1-s] = lens[0]
    else:
        maxs = lens[1-s::2].max(), lens[s::2].max() 

    return maxs # Positive, negative max lens

示例运行 -

In [227]: data
Out[227]: 
    A
0   0
1  -5
2   2
3   3
4  -3
5  -4
6  -4
7  -2
8  -1
9   5
10  6
11  7
12  3
13 -1

In [228]: max_interval_lens(data['A'].values)
Out[228]: (4, 5)
相关问题