比较不同长度的pandas数据帧

时间:2016-10-19 12:21:46

标签: python pandas dataframe

我有两个不同长度的数据帧,都按日期索引。我需要两个数据帧具有相同的日期,即。删除最长数据帧中的额外条目。

我发现我可以重置索引并使其成为另一个列,然后将该列称为pandas数据集并与其他数据系列进行比较,为我提供一个只有较短数据帧中的条目的pandas系列:

df1 = ...
df2 = ...
dfadj = df1.reset_index(['Date'])
dfstock = dfadj['Date'][dfadj['Date'].isin(dfindex['Date'])]

但是我需要从这些值中找到索引位置,然后在另一步中从最长的数据帧中删除它。我错过了一个更合乎逻辑和/或更简单的完全不同的approch?

1 个答案:

答案 0 :(得分:4)

您可以使用Index.intersection,然后按ix选择df2中的数据:

idx = df2.index.intersection(df1.index)
print (idx)
DatetimeIndex(['2015-02-24', '2015-02-25', '2015-02-26', '2015-02-27',
               '2015-02-28', '2015-03-01', '2015-03-02', '2015-03-03',
               '2015-03-04', '2015-03-05'],
              dtype='datetime64[ns]', freq='D')

print (df2.ix[idx])
             b
2015-02-24  10
2015-02-25  11
2015-02-26  12
2015-02-27  13
2015-02-28  14
2015-03-01  15
2015-03-02  16
2015-03-03  17
2015-03-04  18
2015-03-05  19

另一个解决方案是使用merge与内联接,什么是deafult,所以可以省略how='inner'

df = pd.merge(df1,df2, left_index=True, right_index=True)

样品:

rng1 = pd.date_range(pd.to_datetime('2015-02-24'), periods=10)
df1 = pd.DataFrame({'a': range(10)}, index=rng1)   
print (df1)
            a
2015-02-24  0
2015-02-25  1
2015-02-26  2
2015-02-27  3
2015-02-28  4
2015-03-01  5
2015-03-02  6
2015-03-03  7
2015-03-04  8
2015-03-05  9

rng2 = pd.date_range(pd.to_datetime('2015-02-24'), periods=20)
df2 = pd.DataFrame({'b': range(10,30)}, index=rng2)  
print (df2)
            b
2015-02-24  10
2015-02-25  11
2015-02-26  12
2015-02-27  13
2015-02-28  14
2015-03-01  15
2015-03-02  16
2015-03-03  17
2015-03-04  18
2015-03-05  19
2015-03-06  20
2015-03-07  21
2015-03-08  22
2015-03-09  23
2015-03-10  24
2015-03-11  25
2015-03-12  26
2015-03-13  27
2015-03-14  28
2015-03-15  29
df = pd.merge(df1,df2, left_index=True, right_index=True)
print (df)
            a   b
2015-02-24  0  10
2015-02-25  1  11
2015-02-26  2  12
2015-02-27  3  13
2015-02-28  4  14
2015-03-01  5  15
2015-03-02  6  16
2015-03-03  7  17
2015-03-04  8  18
2015-03-05  9  19

如果需要删除某些列,请使用drop

print (df.drop(['a'], axis=1))
             b
2015-02-24  10
2015-02-25  11
2015-02-26  12
2015-02-27  13
2015-02-28  14
2015-03-01  15
2015-03-02  16
2015-03-03  17
2015-03-04  18
2015-03-05  19
相关问题