簡體   English   中英

如何比較兩個數據框並返回具有差異的列?

[英]How to compare two dataframes and return a column with difference?

我正在准備一個數據框來存儲員工技能的變化。

我想比較兩個帶有以下標簽的表:“員工姓名”,“技能名稱”,“年份”和“得分”。 第二年雇用了一些員工,並增加了一些技能。 我想檢查兩個數據框內是否缺少員工或技能並填補空白,以使數據框的形狀相同。

dataset = dataset[['Employee Name', 'Skill Name', 'Year', 'Score']]

min_y = dataset['Year'].min()
max_y = dataset['Year'].max()

ds1 = ds1.sort_values(['Employee Name', 'Skill Name'], ascending=[True, False])
ds2 = ds2.sort_values(['Employee Name', 'Skill Name'], ascending=[True, False])

ds1 = dataset[dataset['Year']==min_y].reset_index().drop(['index'], axis=1).drop(['Year'], axis=1)
ds2 = dataset[dataset['Year']==max_y].reset_index().drop(['index'], axis=1).drop(['Year'], axis=1)

dsBool = (ds1 != ds2).stack()
dsdiff = pd.concat([ds1.stack()[dsBool], ds2.stack()[dsBool]], axis=1)
dsdiff.columns=["Old", "New"]

當前,由於兩個DataFrame之間的形狀差異,比較這兩個表會導致錯誤:只能比較標記相同的DataFrame對象

在比較之前,請嘗試確保兩個數據幀的索引相同:

ds1 = dataset[dataset['Year']==min_y].drop(['Year'], axis=1).reset_index(drop=True)
ds2 = dataset[dataset['Year']==max_y].drop(['Year'], axis=1).reset_index(drop=True)

然后執行比較:

dsBool = (ds1 != ds2).stack()

編輯:

實際上,我認為您的原始帖子可能包含錯誤順序的代碼。 請嘗試以下操作:

dataset = dataset[['Employee Name', 'Skill Name', 'Year', 'Score']]

dataset.sort_values(['Employee Name', 'Skill Name'], ascending=[True, False], inplace=True)

ds1 = dataset[dataset['Year'] == dataset['Year'].min()].drop(['Year'], axis=1).reset_index(drop=True)
ds2 = dataset[dataset['Year'] == dataset['Year'].max()].drop(['Year'], axis=1).reset_index(drop=True)

dsBool = (ds1 != ds2).stack()
dsdiff = pd.concat([ds1.stack()[dsBool], ds2.stack()[dsBool]], axis=1)
dsdiff.columns=["Old", "New"]

可以理解,形狀錯誤是由於新員工的增加和現有員工技能的更新。 要找出丟失的值,可以將這些數據框合並,然后刪除重復的條目。 這樣,剩下的唯一條目將是在兩個數據幀中都不同的條目。

temp = pd.concat((ds1, ds2), axis = 0)
temp = temp.drop_duplicates(subset = 'Employee Name', keep = False, inplace = True)
# keep = False ensures that all repeating entries are considered duplicates

現在,臨時數據幀包含所有在前兩個數據幀中不同的條目。 可以在形狀匹配的數據框中搜索和編輯它們。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM