簡體   English   中英

pandas 中特定數字的累積結果

[英]Cumulative result with specific number in pandas

這是我的 DataFrame:

index, value
10, 109
11, 110
12, 111
13, 110
14, 108
15, 106
16, 100

我想基於乘以 0,05 和累積結果來構建另一列。

index, value, result
10, 109, 109
11, 110, 109 + (0,05 * 1) = 109,05
12, 111, 109 + (0,05 * 2) = 109,1
13, 110, 109 + (0,05 * 3) = 109,15
14, 108, 109 + (0,05 * 4) = 109,2
15, 106, 109 + (0,05 * 5) = 109,25
16, 100, 109 + (0,05 * 6) = 109,3

我嘗試嘗試使用 shift 和 cumsum,但沒有任何效果。 你能給我一個建議嗎?

現在我做類似的事情:

counter = 1
result = {}
speed = 0,05
for item in range (index + 1, last_row_index + 1):
    result[item] = result[first_index] + speed * counter
    counter += 1

PS 在您的回答中,我編輯了列結果。 請不要怪我。 我真的很傻,但我努力成長。

謝謝大家的答案

使用numpy

df['result'] = df['value'].iloc[0]*1.05**np.arange(len(df))

Output:

   index  value      result
0     10    109  109.000000
1     11    110  114.450000
2     12    111  120.172500
3     13    110  126.181125
4     14    108  132.490181
5     15    106  139.114690
6     16    100  146.070425

編輯問題后:

df['result'] = df['value'].iloc[0]+0.05*np.arange(len(df))

output:

   index  value  result
0     10    109  109.00
1     11    110  109.05
2     12    111  109.10
3     13    110  109.15
4     14    108  109.20
5     15    106  109.25
6     16    100  109.30

如果索引是連續的

df['result'] = (df['index'] - df['index'][0]) * 0.05 + df['value'][0]

或不:

df['result'] = df.value.reset_index().index * 0.05 + df.value[0]
df['result'] = np.arange(len(df)) * 0.05
df['result'] = df['value'].add(df['result'])
print(df)

Output:

   value  result
0    109  109.00
1    110  110.05
2    111  111.10
3    110  110.15
4    108  108.20
5    106  106.25
6    100  100.30

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM