我的意见:
df1 = pd.DataFrame({'frame':[ 1,1,1,2,3,0,1,2,2,2,3,4,4,5,5,5,8,9,9,10,],
'label':['GO','PL','ICV','CL','AO','AO','AO','ICV','PL','TI','PL','TI','PL','CL','CL','AO','TI','PL','ICV','ICV'],
'user': ['user1','user1','user1','user1','user1','user1','user1','user1','user1','user1','user1','user1','user1','user1','user1','user1','user1','user1','user1','user1']})
df2 = pd.DataFrame({'frame':[ 1, 1, 2, 3, 4,0,1,2,2,2,4,4,5,6,6,7,8,9,10,11],
'label':['ICV','GO', 'CL','TI','PI','AO','GO','ICV','TI','PL','ICV','TI','PL','CL','CL','CL','AO','AO','PL','ICV'],
'user': ['user2','user2','user2','user2','user2','user2','user2','user2','user2','user2','user2','user2','user2','user2','user2','user2','user2','user2','user2','user2']})
df_c = pd.concat([df1,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_unq= pd.pivot_table(m_df,
columns='cross',
index='label_x',
values='frame',
aggfunc=pd.Series.nunique,fill_value=0,margins=True)
pv_mc = pd.pivot_table(m_df,
columns='cross',
index='label_x',
values='frame',
aggfunc=pd.Series.count,fill_value=0,margins=True)
但这带来了一些问题:
首先,我可以计算图片中描述的匹配和错配的“简单”总数(列All
),或者它的“复制”为pv_m
中的AO
,或者错误的数字为pv_m_unq
中的CL
第二,我认为merge
方法在我使用int时并不聪明,因为如果frame
+label
在df中重复(这种情况经常发生),在合并的df中,我会得到df1中的行数X df2中这个特定frame
+label
的行数
我想也许有一个更聪明的方法来比较df和透视它们
您在margin total上得到了意外的结果,因为margin使用了传递给} )进行计算的相同函数,并且这两行中的
aggfunc
(即本例中的^{Matched
和Mismatched
的值都与1
相同(因此只有一个唯一的1
)。(您当前正在获取frame
id的唯一计数)通过在代码的最后一行中使用^{} 而不是
frame
id的唯一计数,您可能可以通过对它们(包括边距,Matched
和Mismatched
)进行计数来或多或少地实现您想要的:结果
编辑
如果只需要将
All
列设为Matched
和Mismatched
的和,则可以按如下方式执行:更改生成
pv_m_unq
而不生成建筑边距的代码:然后,我们为每一行创建
All
列作为Matched
和Mismatched
的和,如下所示:最后,为每个列创建行
All
作为Matched
和Mismatched
的和,并将其作为最后一行附加,如下所示:结果:
您可以像这样使用
isin()
函数:相关问题 更多 >
编程相关推荐