python - 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 太陌生,并试图学习如何使用它。
解决方案
我想我会使用合并将它们加入数据集,然后寻找差异。
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 是每个数据帧中常用命名列的默认后缀。您不能使用suffixes
merge 中的参数重新定义这些后缀。
推荐阅读
- docker - 如何使用 ubuntu:20.04 基础在 docker 中运行 wine(适用于 ubuntu:18.04 基础)
- expression - PhpStorm 为项目文件生成 MD5Sum
- payment-gateway - razorpay Add On 是如何工作的?我们可以在订阅中添加一次,并且以后无需更新即可使用?
- php - 如何在 laravel eloquent 的订单表中计算相同的产品?我是 Laravel 新用户
- javascript - 期望 Jest 中的超时被拒绝
- python - 一个程序来排序球员的分数,按降序显示他们的分数
- javascript - 如何使用 forEach 循环为每个类附加一个新的 div?
- vue.js - 如何将函数传递给Vue中的子组件?
- git - Github:如何跨同一存储库的多个分支工作
- python - 合并除两个特定列之外的所有列元素