我有一個包含一系列數字的 Pandas 資料框:
df = pd.DataFrame({'deduction':[10,60,70,50,60,10,10,60,60,20,50,20,10,90,60,70,30,50,40,60]})
deduction
0 10
1 60
2 70
3 50
4 60
5 10
6 10
7 60
8 60
9 20
10 50
11 20
12 10
13 90
14 60
15 70
16 30
17 50
18 40
19 60
我想計算這些數字的累積差異,從一個較大的數字(即<base_number> - 10 - 60 - 70 - 50 - ...)開始。
我當前的解決方案是否定所有數字,將(正)較大的數字添加到資料幀中,然后呼叫cumsum():
# Compact:
(-df['deduction'][::-1]).append(pd.Series([start_value], index=[-1]))[::-1].cumsum().reset_index(drop=True)
# Expanded:
total_series = (
# Negate
(-df['deduction']
# Reverse
[::-1])
# Add the base value to the end
.append(pd.Series([start_value]))
# Reverse again (to put the base value at the beginning)
[::-1]
# Calculate cumulative sum (all the values except the first are negative, so this will work)
.cumsum()
# Clean up
.reset_index(drop=True)
)
但我想知道是否可能有一個更短的解決方案,它沒有附加到系列中(我聽說這是不好的做法)。
(它不需要放在資料框中;一個系列,就像我在上面所做的那樣,就可以了。)
uj5u.com熱心網友回復:
df['total'] = start_value - df["deduction"].cumsum()
如果您需要系列開頭的起始值,則移動并插入(有幾種方法可以做到,這是其中之一)
df['total'] = -df["deduction"].shift(1).fillna(-start_value).cumsum()
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/355466.html
上一篇:用Pandas的列的平均值替換值
