Quantcast
Channel: Count and summation of positive and negative number sequences - Stack Overflow
Viewing all articles
Browse latest Browse all 15

Answer by Walter Tross for Count and summation of positive and negative number sequences

$
0
0

As for Python, someone will come up with a solution using the pandas library. In the meantime, here is a simple proposal:

class Combiner:    def __init__(self):        self.index = self.seq_index = self.summation = 0    def combine(self, value):        self.index += 1        if value * self.summation <= 0:            self.seq_index = 1            self.summation = value        else:            self.seq_index += 1            self.summation += value        return self.index, value, self.seq_index, self.summationc = Combiner()lst = [c.combine(v) for v in x]for t in lst:    print(f"{t[0]:3} {t[1]:7.3f} {t[2]:3} {t[3]:7.3f}")

Output:

  1  -0.010   1  -0.010  2   0.003   1   0.003  3  -0.002   1  -0.002  4   0.018   1   0.018  5   0.002   2   0.020  6   0.006   3   0.026  7  -0.012   1  -0.012  8   0.014   1   0.014  9  -0.017   1  -0.017 10  -0.007   2  -0.024 11   0.002   1   0.002 12   0.002   2   0.004 13  -0.004   1  -0.004 14   0.015   1   0.015 15   0.002   2   0.017 16  -0.001   1  -0.001 17  -0.008   2  -0.009 18   0.010   1   0.010 19  -0.018   1  -0.018 20   0.046   1   0.046

If you need separate lists, you can do

idxs, vals, seqs, sums = (list(tpl) for tpl in zip(*lst))

or, if iterators are OK, simply

idxs, vals, seqs, sums = zip(*lst)

(explanation here)


Viewing all articles
Browse latest Browse all 15

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>