检查两个不同Excel文件/数据帧中具有相同keyvalue的多行值的有效方法是什么?

2024-09-29 23:27:31 发布

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

我有两个excel文件。两者都包含关于相同数据对象的信息。数据对象由对象编号(列ON)标识,该编号的类型为str

example:

Table 1                                Table 2
ON      colA  colB  colToUpdate         ON   colImportant
1.2.3    abc   123                      1.2.3      inf
2.9.6    ert   987                      1.2.3      mat
3.5.0    nms   021                      2.9.6      mat
                                        2.9.6      tr
                                        2.9.6      ch
                                        3.5.0      tr

myValues={inf, ch}

Task:

我需要检查表2中的colImportant值之一是否在我的myValues中,并且该数据对象(具有相同对象编号的行)需要在df1中的colToUpdate中获取值“Ok”

expectation:

new Table 1
   ON      colA  colB  colToUpdate        
   1.2.3    abc   123     Ok                
   2.9.6    ert   987     Ok               
   3.5.0    nms   021     NaN     

我考虑将两者保存在一个单独的数据帧中(表1 inddf1和表2 indf2),并在更新df1中的下一列时始终在df2中搜索相同的对象号。但这将始终搜索整个df2(大约有30000个数据对象,这意味着df1中有30000行。在df2中,有75000行,因为一个数据对象可以与另一个值一起多次存储在colImportant中,如上所示)

另一个想法是在{}中创建一个{},我将{}中的所有值放在{}中,使用类似{}的分隔符(但是,我需要一些将多行合并到{}中的一行,然后通过{}合并dfs)。然后,当我想根据某些条件更新df1中的行时,我必须检查分割的值。 完成后,我可以删除tempCol。 应该是这样的:

  Table 1                                
    ON      colA  colB  colToUpdate tempCol       
    1.2.3    abc   123               inf,mat       
    2.9.6    ert   987               mat,tr,ch      
    3.5.0    nms   021               inf

Tags: 数据对象ontable编号infdf1abc
1条回答
网友
1楼 · 发布于 2024-09-29 23:27:31

以下是我的方法:

tmp_df = df2.groupby('ON').colImportant.apply(lambda x: 'OK' if (~x.isin(myValues)).any() 
                                                             else np.nan)

df1=df1.merge(tmp_df.reset_index()[['colImportant']], 
               left_on=df1.ON, 
               right_on=tmp_df.index).drop('key_0', axis=1)

输出:

+  +   -+    +        +
|    | ON    | colA   | colImportant   |
|  +   -+    +        |
|  0 | 1.2.3 | abc    | OK             |
|  1 | 2.9.6 | ert    | OK             |
|  2 | 3.5.0 | nms    | nan            |
+  +   -+    +        +

不完美,但我想你可以解决

相关问题 更多 >

    热门问题