Skip to content Skip to sidebar Skip to footer

Count Consecutive Positive And Negative Values In A List

I created a Dataframe with two columns and would like to append them based on the counting of values from other array. cols = ['count_pos','count_neg'] df_count = pd.DataFrame(colu

Solution 1:

Count consecutive groups of positive/negative values using groupby:

s = pd.Series(y)
v = s.gt(0).ne(s.gt(0).shift()).cumsum()

pd.DataFrame(
    v.groupby(v).count().values.reshape(-1, 2), columns=['pos', 'neg']
)

   pos  neg
0    1    2
1    4    2

Solution 2:

Adapted from @cs95's answer:

a = pd.Series([-1, 2, 15, 3, 45, 5, 23, 0, 6, -4, -8, -5, 3, 
-9, -7, -36, -71, -2, 25, 47, -8])

defpos_neg_count(a):
    v = a.ge(0).ne(a.ge(0).shift()).cumsum()
    vals = v.groupby(v).count().values
    cols = ['pos', 'neg'] if a[0] >= 0else ['neg', 'pos']
    try:
        result = pd.DataFrame(vals.reshape(-1, 2), columns=cols)
    except ValueError:
        vals = np.insert(vals, len(vals), 0)
        result = pd.DataFrame(vals.reshape(-1, 2), columns=cols)
    return result

pos_neg_count(a)
#       neg pos#   0     1   8#   1     3   1#   2     5   2#   3     1   0

I think, this would take care of cases where the array being reshaped has odd no. of elements.

Post a Comment for "Count Consecutive Positive And Negative Values In A List"