我有两个具有相同索引的数据框。我想根据一个方程式向其中一个数据框添加一列,为此我需要来自索引相同的另一个数据框的一行中的值。 使用
df2['B'].loc[df2['Date'] == df1['Date']]
我收到“只能比较标记相同的Series对象”的错误
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 |
+----------------+
答案 0 :(得分:0)
这应该有效。如果不是,则只需使用列名,因为这两个表中的列名相似。 A_y是df2 ['A']列(由于相似而自动重命名)
df1['B']=df1.merge(df2, left_index=True, right_index=True)['A_y']+1
答案 1 :(得分:0)
我想现在我将不得不通过将df2的剪切克隆到df1的索引来解决这个问题
dfc = df2
t = list(df1['Date'])
dfc = dfc.loc[dfc['Date'].isin(t)]
df1['B'] = 1 + dfc['A']