我想计算一系列的“结转”。这将计算每行的值,然后将其添加到先前计算的值(对于上一行)。
我怎么在熊猫里这样做?
decay = 0.5
test = pd.DataFrame(np.random.randint(1,10,12),columns = ['val'])
test
val
0 4
1 5
2 7
3 9
4 1
5 1
6 8
7 7
8 3
9 9
10 7
11 2
decayed = []
for i, v in test.iterrows():
if i ==0:
decayed.append(v.val)
continue
d = decayed[i-1] + v.val*decay
decayed.append(d)
test['loop_decay'] = decayed
test.head()
val loop_decay
0 4 4.0
1 5 6.5
2 7 10.0
3 9 14.5
4 1 15.0
考虑使用cumsum()
的矢量化版本,其中累积求和(val * decay)与第一个val。
但是,你需要减去第一个(val *衰减),因为cumsum()
包含它:
test['loop_decay'] = (test.ix[0,'val']) + (test['val']*decay).cumsum() - (test.ix[0,'val']*decay)
您可以利用pd.Series.shift()
创建一个val [i]和val [i-1]的数据帧,然后在单个轴上应用您的函数(在本例中为1):
# Create a series that shifts the rows by 1
test['val2'] = test.val.shift()
# Set the first row on the shifted series to 0
test['val2'].ix[0] = 0
# Apply the decay formula:
test['loop_decay'] = test.apply(lambda x: x['val'] + x['val2'] * 0.5, axis=1)