繁体   English   中英

哪种有效的方法可以检查两个不同的excel文件/数据框中具有相同键值的多行的值?

[英]Which is an efficient way for checking values of multiple rows with the same keyvalue in two different excel-files/dataframes?

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

例:

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}

任务:

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

期望:

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 IND保存df1和表2中df2 )始终搜索相同的对象号在df2在更新下一列时df1 但这总是会搜索整个df2df2有30000个数据对象,这意味着df1有30000行。在df2 ,有75000行,因为一个数据对象可以与colImportant另一个值多次存储,如您在上面看到的)。

另一个想法是在df1中创建一个tempCol在其中我将所有来自colImportant的值放在df2并使用分隔符, (但是,我需要将多行合并到df2然后将dfs合并为'ON' ) 。 然后,当我想通过某些条件更新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

这是我的方法:

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

不完美,但我认为您可以解决。

暂无
暂无

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

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