0

I have two dataframes, df1 and df2, each in the following format with the same index and different values:

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

I need to compare the two dataframes where values of df1 < df2 and get only those values for which the comparison stands true with their respective indices in a third dataframe df_new.

1 Answers1

2

I would suggest that you merge your two data frames based on the index so that you can compare the values between each columns.

Try this:

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']

It will return you the following dataframe:

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

Here is the link to the merge method: pandas.DataFrame.merge

Alexis.Rolland
  • 5,724
  • 6
  • 50
  • 77