首页 > 解决方案 > Python pandas 比较 2 Microsoft Excel 并输出更改

问题描述

我正在尝试使用 Python pandas 来确定需要对某些行进行的更改。

数据1

name   contract   id    unit  qty  location
siteA  00012345  A001   pcs    1    M.K.141.1
siteA  00012345  A002   pcs    2    M.K.141.1
siteA  00012345  A003   pcs    3    M.K.141.1
siteA  00012345  A004   pcs    12   M.K.141.1
siteA  00012345  A005   pcs    26   M.K.141.1
siteA  00012345  A006   pcs    2    M.K.141.1
siteB  00012345  A001   pcs    2    M.K.285.1
siteB  00012345  A003   pcs    3    M.K.285.1
siteB  00012345  A004   pcs    5    M.K.285.1
siteB  00012345  A005   pcs    10   M.K.285.1
siteB  00012345  A006   pcs    11   M.K.285.1

数据2

name   id   unit   qty
siteA  A001  pcs    1
siteA  A002  pcs    4 
siteA  A003  pcs    6 
siteA  A004  pcs    12
siteA  A005  pcs    28
siteB  A001   pcs   2 
siteB  A003   pcs   6 
siteB  A004   pcs   5 
siteB  A005   pcs   33
siteB  A006   pcs   11

我想弄清楚的是比较data2和data1,并分别检查siteA和siteB之间的数量差异,并修改data1中的数量

需要一些先机,因为查看 pandas 文档需要我太长时间才能理解该做什么..

谢谢!

我目前拥有的代码片段:

import pandas as pd

df1 = pd.read_excel(r'D:\data1.xlsx', 'Sheet1')
df2 = pd.read_excel(r'D:\data2.xlsx', 'Sheet1')

for index, row in df1.iterrow():
    pass

太糟糕了,我对 pandas 太陌生,并试图学习如何使用它。

标签: pythonpandas

解决方案


我想我会使用合并将它们加入数据集,然后寻找差异。

data1.merge(data2, on=['name','id','unit']).query('qty_x != qty_y')

输出:

    name  contract    id unit  qty_x   location  qty_y
1  siteA     12345  A002  pcs      2  M.K.141.1      4
2  siteA     12345  A003  pcs      3  M.K.141.1      6
4  siteA     12345  A005  pcs     26  M.K.141.1     28
6  siteB     12345  A003  pcs      3  M.K.285.1      6
8  siteB     12345  A005  pcs     10  M.K.285.1     33

其中 _x 和 _y 是每个数据帧中常用命名列的默认后缀。您不能使用suffixesmerge 中的参数重新定义这些后缀。


推荐阅读