Skip to main content
 首页 » 编程设计

python之使用 Datetimeindex 选择行

2025年05月04日9Terrylee

我正在使用 Pandas Python 库比较两个数据框,每个数据框都包含一列日期和两列值。其中一个数据帧,称为 LongDF,包含比另一个数据帧更多的日期,称为 ShortDF。这两个数据帧都使用 pandas.tseries.index.DatetimeIndex 按日期编制索引,请参见下文(我将两者都缩短只是为了演示)。

LongDF

╔════════════╦════════╦════════╗ 
║ Date       ║ Value1 ║ Value2 ║ 
╠════════════╬════════╬════════╣ 
║ 1990-03-17 ║ 6.84   ║ 1.77   ║ 
║ 1990-03-18 ║ 0.99   ║ 7.00   ║ 
║ 1990-03-19 ║ 4.90   ║ 8.48   ║ 
║ 1990-03-20 ║ 2.57   ║ 2.41   ║ 
║ 1990-03-21 ║ 4.10   ║ 8.33   ║ 
║ 1990-03-22 ║ 8.86   ║ 1.31   ║ 
║ 1990-03-23 ║ 6.01   ║ 6.22   ║ 
║ 1990-03-24 ║ 0.74   ║ 1.69   ║ 
║ 1990-03-25 ║ 5.56   ║ 7.30   ║ 
║ 1990-03-26 ║ 8.05   ║ 1.67   ║ 
║ 1990-03-27 ║ 8.87   ║ 8.22   ║ 
║ 1990-03-28 ║ 9.00   ║ 6.83   ║ 
║ 1990-03-29 ║ 1.34   ║ 6.00   ║ 
║ 1990-03-30 ║ 1.69   ║ 0.40   ║ 
║ 1990-03-31 ║ 8.71   ║ 3.26   ║ 
║ 1990-04-01 ║ 4.05   ║ 4.53   ║ 
║ 1990-04-02 ║ 9.75   ║ 4.79   ║ 
║ 1990-04-03 ║ 7.74   ║ 0.44   ║ 
╚════════════╩════════╩════════╝ 

ShrotDF

╔════════════╦════════╦════════╗ 
║ Date       ║ Value1 ║ Value2 ║ 
╠════════════╬════════╬════════╣ 
║ 1990-03-25 ║ 1.98   ║ 3.92   ║ 
║ 1990-03-26 ║ 3.37   ║ 3.40   ║ 
║ 1990-03-27 ║ 2.93   ║ 7.93   ║ 
║ 1990-03-28 ║ 2.35   ║ 5.34   ║ 
║ 1990-03-29 ║ 1.41   ║ 7.62   ║ 
║ 1990-03-30 ║ 9.85   ║ 3.17   ║ 
║ 1990-03-31 ║ 9.95   ║ 0.35   ║ 
║ 1990-04-01 ║ 4.42   ║ 7.11   ║ 
║ 1990-04-02 ║ 1.33   ║ 6.47   ║ 
║ 1990-04-03 ║ 6.63   ║ 1.78   ║ 
╚════════════╩════════╩════════╝ 

我想做的是引用每个数据集中同一天发生的数据,将两组的数据放入一个公式中,如果它更大将日期和值粘贴到另一个数据框中。

我假设我应该使用类似for row in ShortDF.iterrows(): 的方法来遍历 ShortDF 上的每个日期,但我不知道如何选择LongDF 上的相应行,使用 DatetimeIndex。

任何帮助将不胜感激

请您参考如下方法:

好的,我现在醒了,使用你的数据你可以做到这一点:

In [425]: 
# key here is to tell the merge to use both sides indices 
merged = df1.merge(df2,left_index=True, right_index=True) 
# the resultant merged dataframe will have duplicate columns, this is fine 
merged 
Out[425]: 
            Value1_x  Value2_x  Value1_y  Value2_y 
Date                                               
1990-03-25      5.56      7.30      1.98      3.92 
1990-03-26      8.05      1.67      3.37      3.40 
1990-03-27      8.87      8.22      2.93      7.93 
1990-03-28      9.00      6.83      2.35      5.34 
1990-03-29      1.34      6.00      1.41      7.62 
1990-03-30      1.69      0.40      9.85      3.17 
1990-03-31      8.71      3.26      9.95      0.35 
1990-04-01      4.05      4.53      4.42      7.11 
1990-04-02      9.75      4.79      1.33      6.47 
1990-04-03      7.74      0.44      6.63      1.78 
 
[10 rows x 4 columns] 
In [432]: 
# now using boolean indexing we want just the rows where there are values larger than 9 and then select the highest value 
merged[merged.max(axis=1) > 9].max(axis=1) 
Out[432]: 
Date 
1990-03-30    9.85 
1990-03-31    9.95 
1990-04-02    9.75 
dtype: float64