基于多个条件和偏移量合并熊猫数据框

时间:2018-07-13 21:40:26

标签: python pandas

我的数据框如下

              Date  Open  High   Low  Close  Volume  Open Interest  ContractYear Commodity Month_Code  ContractMonth Filename    CY
292715  03/04/1968  8.99  8.99  8.99   8.99       0              1          1969        ZL          F              1  ZL1969F  1968
292716  03/05/1968  9.02  9.02  8.96   8.96       1              2          1969        ZL          F              1  ZL1969F  1968
292717  03/06/1968  8.99  8.99  8.99   8.99       0              2          1969        ZL          F              1  ZL1969F  1968
292718  03/07/1968  9.01  9.01  9.01   9.01       0              2          1969        ZL          F              1  ZL1969F  1968
292719  03/08/1968  9.03  9.04  9.03   9.04       1              3          1969        ZL          F              1  ZL1969F  1968
292720  03/11/1968  9.03  9.04  9.01   9.01       9             10          1969        ZL          F              1  ZL1969F  1968
292721  03/12/1968  9.01  9.01  9.01   9.01       0             10          1969        ZL          F              1  ZL1969F  1968
292722  03/13/1968  9.00  9.00  9.00   9.00       0             10          1969        ZL          F              1  ZL1969F  1968
292723  03/14/1968  9.03  9.03  9.03   9.03       1             11          1969        ZL          F              1  ZL1969F  1968
292724  03/15/1968  8.97  9.01  8.97   9.01       1             12          1969        ZL          F              1  ZL1969F  1968

我正在尝试从数据框中提取值并将其合并,如下所示:

df1 = df[(df.Commodity == c) & (df.ContractMonth == n)]

df2 = df[(df.Commodity == c) & (df.ContractMonth == f) & (df.ContractYear == (df.ContractYear) +1)]

tempdf = pd.merge(df1, df2, how = 'inner', on = 'Date')

对于df2,我尝试将过滤器值偏移1或下一年。上面的代码/逻辑似乎不起作用。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

使用shift,它会创建一个新的序列,该序列会偏移给定的行数:

df2 = df[(df.Commodity == c) & (df.ContractMonth == f) & (df.ContractYear == (df.ContractYear.shift(-1))]