从索引相等的其他数据帧中选择值

2024-04-25 08:02:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个索引相同的数据帧。我想根据一个等式向其中一个数据帧添加一列,我需要另一个数据帧中索引相同的行的值。 使用

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

我得到“只能比较相同标签的系列对象”-错误

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 |
+----------------+


Tags: the数据对象dateindexis错误标签
2条回答

这应该行得通。如果不是,只需使用列名,因为它们在两个表中都是相似的。A_y是df2['A']列(由于相似性而自动命名)

df1['B']=df1.merge(df2, left_index=True, right_index=True)['A_y']+1

我想现在我必须通过将df2的克隆剪切到df1的索引来解决这个问题

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

df1['B'] = 1 + dfc['A']

相关问题 更多 >