【发布时间】:2021-03-22 09:52:33
【问题描述】:
结果左连接中的行数比左数据框中的行数多。
# Importing Pandas and changing it's call to pd
import numpy as np
import pandas as pd
SalesDF = pd.read_csv(r"C:\Users\USER\Documents\Reports\SalesForAnalysis.csv")
print("This is the Sales shape")
print(SalesDF.shape)
CustInfoDF = pd.read_csv(r"C:\Users\USER\Documents\Cust.csv")
# This reassigns the df so that the rows with a NaN in the Account Number it doesn't appear
CustInfoDF = CustInfoDF[CustInfoDF['Account Number'].notna()]
# Merges the two dataframes on SalesDF with "Cust Number" as the key
MergeDF = pd.merge(SalesDF, CustInfoDF, how="left", left_on="Cust Number", right_on="Account Number")
print("This is the Merge Shape ")
print(MergeDF.shape)
# Reduced the number of columns to the selected columns
CutDF = MergeDF[["Customer", "Invoice #", "E-mail Address", "Phone", "Clerk", "Total", "Date"]]
CutDF.drop_duplicates()
print("This is the Cut shape ")
print(CutDF.shape)
这是运行程序后的结果
This is the Sales shape
(5347, 61)
This is the Merge Shape
(6428, 83)
This is the Cut shape
(6428, 7)
Process finished with exit code 0
CutDF 最多只能有 5347 行。我有一个 drop_duplicates 方法,但我仍然得到相同的结果。
我看到了这个pandas left join - why more results? 和inner join/merge in pandas dataframe give more rows than left dataframe,但我并没有真正在这些中看到解决方案。
任何帮助将不胜感激。
【问题讨论】:
-
什么是
SalesDF['Cust Number'].duplicated().any()? -
恐怕我不明白这个问题。你能改写一下吗?
标签: python pandas dataframe merge left-join