我的輸入:
df1 = pd.DataFrame({'frame':[ 1,1,1,2,3],
'label':['GO','PL','ICV','CL','AO']})
df2 = pd.DataFrame({'frame':[ 1, 1, 2, 3, 4],
'label':['ICV','GO', 'CL','TI','PI']})
df_c = pd.concat([df1,df2])
我嘗試比較兩個 df, frameby frame,并檢查labelin 是否df1存在于相同的framein 中df2。并對結果進行一些計算(例如樞軸)
那我的代碼:
m_df = df1.merge(df2,on=['frame'],how='outer' )
m_df['cross']=m_df.apply(lambda row: 'Matched'
if row['label_x']==row['label_y']
else 'Mismatched', axis='columns')
pv_m = pd.pivot_table(m_df,columns='cross',index='label_x',values='frame', aggfunc=pd.Series.nunique,margins=True, fill_value=0)
但這會產生一個問題:

在列All錯誤值。如您所見GO,ICV 我預計總共有 2 個,而不是現在的 1 個。
我想也許有一種更聰明的方法來比較 df 并旋轉它們?
uj5u.com熱心網友回復:
您可以使用這樣的isin()功能:
df3 =df1[df1.label.isin(df2.label)]
uj5u.com熱心網友回復:
您在保證金總額上得到了意想不到的結果,因為保證金正在使用傳遞給aggfunc(即pd.Series.nunique在這種情況下)的相同函式進行計算,Matched并且Mismatched這兩行中的和 的值都相同1(因此只有一個唯一值1) . (您目前正在獲得frameid 的唯一計數)
也許,你可以實作更多或更少的你想要的東西通過采取數對他們(包括保證金,Matched和Mismatched),而不是獨特的計數frame的ID,通過使用pd.Series.count而不是代碼的最后一行:
pv_m = pd.pivot_table(m_df,columns='cross',index='label_x',values='frame', aggfunc=pd.Series.count, margins=True, fill_value=0)
結果
cross Matched Mismatched All
label_x
AO 0 1 1
CL 1 0 1
GO 1 1 2
ICV 1 1 2
PL 0 2 2
All 3 5 8
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/331189.html
