0

I have two dataframes with the same index. I would like to add a column to one of those dataframes based on an equation for which I need the value from a row of another dataframe where the index is the same. Using

df2['B'].loc[df2['Date'] == df1['Date']]

I get the 'Can only compare identically-labeled Series objects' -error

df1
+-------------+
| Index     A |
+-------------+
| 3-2-20    3 |
| 4-2-20    1 |
| 5-2-20    3 |
+-------------+

df2
+----------------+
|   Index   A    |
+----------------+
| 1-2-20    2    |
| 2-2-20    4    |
| 3-2-20    3    |
| 4-2-20    1    |
| 5-2-20    3    |
+----------------+


df1['B'] = 1 + df2['A'].loc[df2['Date'] == df1['Date']] , the index is a date but in my real df I have also a col called Date with the same values

df1 desired
+----------------+
| Index     A  B |
+----------------+
| 3-2-20    3  4 |
| 4-2-20    1  2 |
| 5-2-20    3  4 |
+----------------+

Luca R
  • 197
  • 2
  • 14
  • 4
    Please provide a [mcve] including sample input and expected output – G. Anderson Aug 12 '20 at 22:44
  • How can I display a table? – Luca R Aug 12 '20 at 23:21
  • 1
    Thank you for providing the sample data. For future reference, see [How to make good pandas examples](https://stackoverflow.com/questions/20109391/how-to-make-good-reproducible-pandas-examples) for a quick and easy guide – G. Anderson Aug 13 '20 at 20:16

2 Answers2

1

This should work. If not, just play with the column names, because they are similar in both tables. A_y is the df2['A'] column (autorenamed because of the similarity)

df1['B']=df1.merge(df2, left_index=True, right_index=True)['A_y']+1
IoaTzimas
  • 10,538
  • 2
  • 13
  • 30
0

I guess for now I will have to settle with doing it by a cut clone of df2 to the indexes of df1

dfc = df2
t = list(df1['Date'])
dfc = dfc.loc[dfc['Date'].isin(t)]

df1['B'] = 1 + dfc['A']
Luca R
  • 197
  • 2
  • 14