我能否在不显式循环的情况下,使用pandas.Series对a
和b
进行数学运算?
In [38]: a = pd.Series([4, 8, 3, 6, 2])
In [39]: b = pd.Series([3, 9, 5, 5, 4])
In [40]: alist = a.tolist()
...: blist = b.tolist()
...: for i in range(len(alist)):
...: diff = max(0, alist[i] - blist[i])
...: try:
...: alist[i + 1] = alist[i + 1] + diff
...: except IndexError:
...: if diff > 0:
...: alist.append(diff)
...: blist[i] = max(0, blist[i] - alist[i])
...:
In [41]: alist
Out[41]: [4, 9, 3, 6, 3]
In [42]: blist
Out[42]: [0, 0, 2, 0, 1]
如果a-b大于零,我会用a和b的差来增加a的下一个值,并从类似累积总和的计算中减去b。