Python 对多索引数据帧上的不同行执行操作

Python 对多索引数据帧上的不同行执行操作,python,pandas,dataframe,Python,Pandas,Dataframe,假设我有以下多索引数据帧 date_a date_b index_a index_b 1 Foo 1/2/2018 1/1/2018 Bar 1/3/2018 12/20/2017 2 Foo 2/4/2018 3/6/2018 Bar 2/2/2017 1/2

假设我有以下多索引数据帧

                     date_a        date_b
index_a   index_b               
1          Foo     1/2/2018     1/1/2018
           Bar     1/3/2018     12/20/2017  
2          Foo     2/4/2018     3/6/2018
           Bar     2/2/2017     1/2/2017
如何生成一个序列,从Foo中获取日期_a,从索引_a索引的条中获取日期_b

index_a   difference_of_a_and_b     
1          1:00:00  
2          2:00:00

我已经找到了一种通过每个索引来实现的方法:

df.loc[1,'Foo']['date_a'] - df.loc[1,'Bar']['date_b'] 

现在,如何使用
DataFrame.xs
对所有索引进行切片并减去:

(pd.to_datetime(df.xs('Foo', level=1)['date_a']) 
     - pd.to_datetime(df.xs('Bar', level=1)['date_b']))

index_a
1    13 days
2   398 days
dtype: timedelta64[ns]

您希望结果如何?输出将只有两行。一系列由索引a索引的数据,类似于:index\u a new\u column 1 1:00:00 2:00:00如果注释中没有任何格式,我无法理解这一点。请编辑您的问题。我已经找到了按每个索引执行的方法:df.loc[1,'Foo']['date\u a']-df.loc[1.Bar']['date\u b']现在,我如何准确地将它添加到所有索引中,谢谢!