簡體   English   中英

基於另一個時間序列在pandas中查找一個序列中的值的差異

[英]Finding the difference of values in a series in pandas based on another time series

我有一個熊貓金融時間序列和一個時間序列“位置”,當趨勢為正時取值為 1,否則為 -1。 位置系列不斷交替 1 和 -1。 有沒有函數或聰明的方法來找到一個積極時期的開始和結束之間的差異? 更具體地說,我想對所有的增量求和,但為了做到這一點,我正在努力尋找一種方法來確定趨勢的起點和終點。 謝謝

如果您將前一個和當前位置值相加,您可以尋找它是 0 的位置,這將是趨勢翻轉的位置。

像這樣:

trend_flipped = df["Trend"] + df["Trend"].shift() == 0
df[trend_flipped]

讓我們假設,你有一個這樣的數據框:

         date  value
0  2020-11-12     10
1  2020-11-13     12
2  2020-11-14     15
3  2020-11-15     17
4  2020-11-16     17
5  2020-11-17     11
6  2020-11-18     12
7  2020-11-19      9
8  2020-11-20      7

並且您想計算上升周期的開始值和結束值之間的差值,然后您會得到以下結果:

          start_date  first_value  last_value  difference
trend_no                                                 
1         2020-11-12           10          17           7
2         2020-11-17           11          12           1

通過執行以下代碼:

# work out the trend of the series
df['difference']= df['value'] - df['value'].shift(1).fillna(0)
df['trend']= np.sign(df['difference'])

# work out the start and end of an ascending series
df['start_ascend']= (df['trend'].shift(-1) > df['trend']).astype('bool')
df.loc[0, 'start_ascend']= True
df['end_ascend']= (df['trend'].shift(-1) < df['trend']).astype('bool')

# assign a number to the ascending trends
# note, that the trends are not yet limited correctly
df['trend_no']= df['start_ascend'].cumsum()

# now work out the borders of the ascending trends
# all records that belong to an ascending trend
# will have df['keep_mask'] == True
df['keep_mask']= np.nan
indexer= df['end_ascend'].shift(1).fillna(False) 
df.loc[indexer, 'keep_mask']= 0.0
df.loc[df['start_ascend'], 'keep_mask']= 1.0
df['keep_mask']= df['keep_mask'].fillna(method='ffill').astype('bool')

# now do the final aggregation
df_res= df[df['keep_mask']].groupby(df['trend_no']).agg(start_date=('date', 'first'), first_value=('value', 'first'), last_value=('value', 'last'))
df_res['difference']= df_res['last_value'] - df_res['first_value']
df_res

如果您想了解上面的步驟實際上做了什么,您可以查看數據框:

         date  value  trend  start_ascend  end_ascend  trend_no  keep_mask
0  2020-11-12     10    1.0          True       False         1       True
1  2020-11-13     12    1.0         False       False         1       True
2  2020-11-14     15    1.0         False       False         1       True
3  2020-11-15     17    1.0         False        True         1       True
4  2020-11-16     17    0.0         False        True         1      False
5  2020-11-17     11   -1.0          True       False         2       True
6  2020-11-18     12    1.0         False        True         2       True
7  2020-11-19      9   -1.0         False       False         2      False
8  2020-11-20      7   -1.0         False       False         2      False

暫無
暫無

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

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