[英]Python pandas Addition and subtraction by sequence
我有一個看起來像這樣的兩列框架:
value,Sequence
12506,-1
12501,-2
12513,-3
12513,1
12521,2
12501,3
12583,-1
12594,-2
12598,1
12589,-1
12615,1
12615,2
12611,3
12573,-1
12593,-2
12564,-3
我想獲得一個新的數據框,其計算值結合了 label
我想如何按順序添加:
1)(值 = 12501)由 label -2,
(值 = 12513)由 label -3
標簽(-3) - 標簽(-2)
12501 - 12513 = -12
2)(值 = 12521)由 label 2,
(值 = 12501)由 label 3
標簽(2) - 標簽(3)
12521 - 12501 = 20
如果在標簽 (-2, 2) 之后沒有 label (-3,3) 並且有 label (-1, 1),則計算如下
3)(值 = 12594)由 label -2,
(值 = 12598)由 label 1
標簽(-2) - 標簽(1)
12594 - 12598 = -4
如果在標簽 (-1,1) 之后有 (1, -1),則不會發生計算
我想得到這樣的數據框:
Calculation
-12
20
-4
4
-29
使用 Pandas 可以做到這一點嗎?
是的,我只是這樣做了,但我真的不知道為什么以及如何設法理解您想要的東西。(編輯:我認為不是,但非常接近)
import pandas as pd
import numpy as np
d = {'value':[12506,12501,12513,12513,
12521,12501,12583,12594,
12598,12589,12615,12615,
12611,12573,12593,12564],
'Sequence':[-1,-2,-3,1,2,3,-1,-2,1,-1,1,2,3,-1,-2,-3]}
df = pd.DataFrame(data=d)
df['value_shifted'] = df["value"].shift(-1)
df['Sequence_shifted'] = df["Sequence"].shift(-1)
new_df = df.where(np.abs(df['Sequence']) == 2).dropna()
new_df['calculation'] = new_df['value'] - new_df['value_shifted']
結果( new_df
):
value Sequence value_shifted Sequence_shifted calculation
1 12501.0 -2.0 12513.0 -3.0 -12.0
4 12521.0 2.0 12501.0 3.0 20.0
7 12594.0 -2.0 12598.0 1.0 -4.0
11 12615.0 2.0 12611.0 3.0 4.0
14 12593.0 -2.0 12564.0 -3.0 29.0
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.