为了账号安全,请及时绑定邮箱和手机立即绑定

在python中计算每组的相同条目

在python中计算每组的相同条目

茅侃侃 2023-06-06 15:59:49
我有以下形式的数据框:group base height weight size0      A     10     5     M0      A     20     5     M1      A     10     10    S2      A      5      5    L我怎样才能得到一个矩阵,它按组计算相似的条目?输出如下所示:compare  base height weight size0,1        3/3  2/3   2/3   2/30,2        3/3  0/3   3/3   2/31,2        2/2  0/2   0/2   0/2
查看完整描述

1 回答

?
侃侃无极

TA贡献2051条经验 获得超10个赞

  • 在解决方案的核心最常见的值

  • 用于itertools.combinations获取有效的组对

  • 在组的组合中比较最频繁的每一行。sum()查找匹配数的真值矩阵

  • 休息正在形成

df = pd.read_csv(io.StringIO("""group base height weight size

0      A     10     5     M

0      A     20     5     M

1      A     10     10    S

2      A      5      5    L"""), sep="\s+")


# columns we're working with

cols = [c for c in df.columns if c!= "group"]


# iterate over combinations of groups

dfx = pd.DataFrame()

for gp in itertools.combinations(df.group.unique(), 2):

    dfg = df.loc[df.group.isin(gp),cols]

    dfx = pd.concat([dfx, 

                     (dfg == dfg.value_counts().index[0])

                     .sum().to_frame().T.assign(gs=len(dfg), compare=",".join(str(e) for e in gp))

                    ])

# rebase 1 as 0 for comparisons

dfx = dfx.reset_index(drop=True).replace(1,0).astype(str)

# format as required

dfx.loc[:,cols] = dfx[cols].apply(lambda x: x+" / " +dfx["gs"])


dfx.drop(columns="gs")

根据高度重量尺寸比较
03 / 32 / 32 / 32 / 30,1
13 / 30 / 33 / 30 / 30,2
22 / 20 / 20 / 20 / 21,2


查看完整回答
反对 回复 2023-06-06
  • 1 回答
  • 0 关注
  • 77 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信