【发布时间】:2020-04-21 17:29:05
【问题描述】:
我从 csv 文件创建了一个发票数据框和一些主数据框
invoice=pd.read_csv('rocaInv4.csv')
soMstr=pd.read_csv('salesOfficeMstr.csv')
custFreightMstr=pd.read_csv('customerCodeFreightMstr.csv')
ratesMstr=pd.read_csv('freightMstr.csv')
pfep=pd.read_csv('pfepMstr.csv')
我根据物料主数据和客户主数据中的可用性删除了一些行。我每次都重新索引。
#checking availability of material
invoice=invoice[invoice['Material'].isin(pfep['Material'])]
invoice=invoice.reset_index(drop=True)
#checking availability of customer details
invoice=invoice[invoice['Ship to Party'].isin(custFreightMstr['Cust No'])]
invoice=invoice.reset_index(drop=True)
#checking validity of sales code
invoice=invoice[invoice['Sales Office'].isin(soMstr['Code'])]
invoice=invoice.reset_index(drop=True)
invoice.shape
#(384, 22)
然后我需要将数据从 master 复制到最终的、干净的 Invoice DataFrame。我没有对两个数据框进行 for 循环,而是对选择的列进行合并。
invoice1=invoice.merge(custFreightMstr[['Cust No','City','Customer Frgt Code']],left_on='Ship to Party',right_on='Cust No', how='left').drop_duplicates()
invoice1.shape
#(388, 25)
即使我在左侧合并,我最终也会多出 4 行。我可以确定哪些行已重复。但我无法确定原因。我在这里做错了什么?
【问题讨论】:
-
对于一个
Ship to Party,您可能在左侧有多个Cust No,因此您可能会获得更多行。没有看到数据就不能说太多,但最终数据框中有多少对(Ship to Party, Cust No)唯一的? -
啊!我以为主人是干净的。我检查并发现4重复,与增加的行完全相同。非常感谢!无论如何指定只使用合并中的第一个匹配项?所有这些都是样本数据,我无法控制它的干净程度
-
您可以在合并之前根据键的重复值删除行。使用带有
subset参数的“drop_duplicates”。 pandas.pydata.org/pandas-docs/stable/reference/api/…