我想將列乘以其下方另一列中的所有值。因此,例如:熊貓乘以下列所有行中的另一列
r5,colC = (r5,colA * r6,colB) +
(r5,colA * r7,colB) +
(r5,colA * r8,colB)
r6,colC = (r6,colA * r7,colB) +
(r6,colA * r8,colB)
暫時我有一個可怕的循環解決方案:
df = pd.DataFrame(data=[[11,0.5],[12,0.4],[12,0.3],[13,0.2],[14,0.1],[15,0.6]],
index=[2001,2002,2003,2004,2005,2006],
columns=['A','B'])
A B
2001 11 0.50
2002 12 0.40
2003 12 0.30
2004 13 0.20
2005 14 0.10
2006 15 0.60
df['C'] = [(df.loc[i]['A']* df['B'][df.index > i]).sum() for i in df.index]
A B C
2001 11 0.50 17.60
2002 12 0.40 14.40
2003 12 0.30 10.80
2004 13 0.20 9.10
2005 14 0.10 8.40
2006 15 0.60 0.00
編輯:
一些速度測試:
%timeit df['C'] = [(df.loc[i]['A']* df['B'][df.index > i]).sum() for i in df.index]
%timeit df['D'] = df.B[::-1].cumsum()[::-1].shift(-1).fillna(0) * df.A
1000 loops, best of 3: 1.69 ms per loop
1000 loops, best of 3: 505 µs per loop
謝謝!比我的方法快3倍以上 – mptevsion