簡體   English   中英

使用先前計算的值(來自同一列)和Pandas Dataframe中另一列的值來計算值

[英]Calculate value using previously-calculated value (from the same column) and value from another column in a Pandas Dataframe

經過數小時試圖學習如何做的事情,我正在與社區聯系。

我從以下內容開始:

                perf
date                
2018-06-01  0.012923
2018-06-02  0.039364
2018-06-03  0.042805
2018-06-04 -0.033214
2018-06-05 -0.021745

需要在新列上計算累計百分比變化,但需要確保計算使用100作為起始值。 因此,我在單行前面加上了100:

                perf  pct_change
date                            
2018-05-31       NaN       100.0
2018-06-01  0.012923         NaN
2018-06-02  0.039364         NaN
2018-06-03  0.042805         NaN
2018-06-04 -0.033214         NaN

我需要得到的是:

                perf  pct_change
date                            
2018-05-31       NaN       100.0
2018-06-01  0.012923    101.2923
2018-06-02  0.039364 105.2795701
2018-06-03  0.042805 109.7860621
2018-06-04 -0.033214 106.1396278

公式類似於pct_change = previous_days_pct_change * ( 1 + perf )

我嘗試了幾種不同的方法,包括for ... in循環,均未成功。

# INCOMPLETE/DOES NOT WORK (adding for illustration purposes only)
for index, row in performance.iterrows():
    curr = performance.loc[index, 'perf']
    pidx = index + pd.DateOffset(-1)
    prev = performance.iloc[[pidx], 'pct_change']
    performance.loc[index, 'pct_change'] = prev * ( 1 + curr )

我也嘗試過:

performance['pct_change'] = performance['pct_change'].shift() * ( 1 + performance['perf'] )

產生:

                perf  pct_change
date                            
2018-05-31       NaN         NaN
2018-06-01  0.012923  101.292251
2018-06-02  0.039364         NaN
2018-06-03  0.042805         NaN
2018-06-04 -0.033214         NaN

但這只是給我一個價值。

我懷疑已經有一種更簡單的方法可以完成我想做的事情,但是我只是找不到。 任何幫助,將不勝感激。 在電子表格中非常容易做到,但是我想學習如何在Pandas中做到這一點。

謝謝

使用cumprod

df['pct_change'] = (df['perf']+1).cumprod() * 100

實現您真正想要的:

pct_change_0 = (perf_0 + 1) * 100
pct_change_1 = pct_change_0 * (perf_1 + 1) = (perf_0 + 1) * (perf_1 + 1) *  100
pct_change_2 = pct_change_1 * (perf_2 + 1) = (perf_0 + 1) * (perf_1 + 1) * (perf_2 + 1) * 100
...

因此,您實際上是在計算perf值的累積乘積(或更准確地說是perf + 1值)。

像這樣:

dates = ['2018-06-01', '2018-06-02', '2018-06-03', '2018-06-04', '2018-06-05']
import datetime as dt
dates = [pd.datetime.date(dt.datetime.strptime(x, "%Y-%m-%d")) for x in dates]
perfs = [0.012923, 0.039364, 0.042805, -0.033214, -0.021745]
df = pd.DataFrame({'perf': perfs}, index=dates)

# The important bit:
df['pct_change'] = ((df['perf'] + 1).cumprod() * 100)

df
#                 perf  pct_change
# 2018-06-01  0.012923  101.292300
# 2018-06-02  0.039364  105.279570
# 2018-06-03  0.042805  109.786062
# 2018-06-04 -0.033214  106.139628
# 2018-06-05 -0.021745  103.831622

暫無
暫無

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

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