具有不同索引类型的两个 DataFrame 之间特定行的差异

Difference of specific rows between two DataFrames with different index types

我有两个DataFramesdf1df2 具有相同的列,但索引类型不同。我尝试创建 df3,它计算两个特定行的成对差异(例如 df1Type1df22022-01-09)。如果有NaN值,我也想在差值DataFramedf3.

中得到一个NaN
df1: 
        ID1 ID2 ID3 ID4
Type                
Type1   1   0   1   NaN
Type2   1   0   0   0.0

df2:
            ID1 ID2 ID3 ID4
2022-01-02  1   0   1   0
2022-01-05  1   0   0   1
2022-01-09  1   1   0   1
2022-01-10  0   0   1   1

df3:
        ID1 ID2 ID3 ID4
Type                
Type1   0   1   1   NaN

为了可重复性:

import datetime
import pandas as pd
import numpy as np

df1 = pd.DataFrame({
    'Type':['Type1', 'Type2'],
    'ID1':[1, 1], 
    'ID2':[0, 0], 
    'ID3':[1, 0],
    'ID4':[np.nan, 0]})
df1 = df1.set_index('Type')

df2 = pd.DataFrame({
    'Date':['2022-01-02', '2022-01-05', '2022-01-09', '2022-01-10'],
    'ID1':[1, 1, 1, 0], 
    'ID2':[0, 0, 1, 0], 
    'ID3':[1, 0, 0, 1],
    'ID4':[0, 1, 1, 1]})
df2 = df2.set_index('Date')
df2.index = pd.to_datetime(df2.index).date

到目前为止,我只用 .diff() 试过。

非常感谢您的建议!

对 select 行使用 DataFrame.loc,使用 DatetimeIndex 的解决方案更简单 - select 通过 '2022-01-09',用 Series 减去一行 DataFrame 并转换输出绝对值:

df2.index = pd.to_datetime(df2.index)


df = df1.loc[['Type1']].sub(df2.loc['2022-01-09']).abs()
print(df)
       ID1  ID2  ID3  ID4
Type                     
Type1    0    1    1  NaN

df2.index = pd.to_datetime(df2.index).date

df = df1.loc[['Type1']].sub(df2.loc[pd.Timestamp('2022-01-09').date()]).abs()
print(df)
       ID1  ID2  ID3  ID4
Type                     
Type1    0    1    1  NaN