比较两个数据帧以获得另一个数据帧中的比较值

时间:2018-02-09 16:22:16

标签: python pandas dataframe

我有两个数据框df1df2,每个数据框采用以下格式,具有相同的索引和不同的值:

       Value
Date
01-01    60
01-02    70
01-03   -80 

我需要比较df1 < df2值的两个数据帧,并且只获得与第三个数据帧df_new中各自索引相对应的那些值。

1 个答案:

答案 0 :(得分:2)

我建议您根据索引合并两个数据框,以便比较每列之间的值。

试试这个:

import pandas

df1 = pandas.DataFrame(
  data=[60, 70, -80],
  index=['01-01', '01-02', '01-03'],
  columns=['Value'])

df2 = pandas.DataFrame(
  data=[59, 69, -79],
  index=['01-01', '01-02', '01-03'],
  columns=['Value'])


df3 = df1.merge(df2, how='outer', left_index=True, right_index=True, suffixes=('_1', '_2'))

df3['Delta'] = df3['Value_2'] - df3['Value_1']

它会返回以下数据框:

       Value_1  Value_2  Delta
01-01       60       59     -1
01-02       70       69     -1
01-03      -80      -79      1

以下是合并方法的链接: pandas.DataFrame.merge