繁体   English   中英

从其他数据框具有相同键的1个数据框更新列

[英]Updating a column from 1 Dataframe where other Dataframe has same keys

我有一个这样的数据框,

Key Group RS
42 23 100
42 41 21
46 23 89
67 10 65

其他数据框是这样的,

Key Group RS
42 41 11
67 10 23

有层次结构:键->组(键内唯一)-> RS。

如果密钥和组与第二个数据帧相同,我想替换第一个数据帧中的RS值。 所以结果应该像

Key Group RS
42 23 100
42 41 11 // updated
46 23 89
67 10 23 // updated

我想使用pandas .update函数,但它不适用于非唯一索引,对于Key来说就是这样,因为它在多行中重复。 我对做什么感到困惑。

设置索引并使用loc分配更新的值。 然后重置索引。
请注意,此方法保留了'RS'列的dtype

d1 = df1.set_index(cols).RS
d2 = df2.set_index(cols).RS
d1.loc[d2.index] = d2
d1.reset_index()

   Key  Group   RS
0   42     23  100
1   42     41   11
2   46     23   89
3   67     10   23

这是一种方法

In [718]: cols = ['Key', 'Group']

In [719]: df2.set_index(cols).combine_first(df1.set_index(cols)).reset_index()
Out[719]:
   Key  Group     RS
0   42     23  100.0
1   42     41   11.0
2   46     23   89.0
3   67     10   23.0

细节

In [720]: df1
Out[720]:
   Key  Group   RS
0   42     23  100
1   42     41   21
2   46     23   89
3   67     10   65

In [721]: df2
Out[721]:
   Key  Group  RS
0   42     41  11
1   67     10  23

pd.concat + drop_duplicates

pd.concat([df1,df2],0).drop_duplicates(['Key','Group'],keep='last')
Out[1107]: 
   Key  Group   RS
0   42     23  100
2   46     23   89
0   42     41   11
1   67     10   23

您可以考虑的一种解决方法是将索引( key )更新为唯一,然后使用您提到的更新方法。 另一种方法可能是遍历两个数组,然后进行更新,但这并不那么优雅。

您可以尝试的另一件事是使用多索引来恢复唯一性。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM