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")
根據 | 高度 | 重量 | 尺寸 | 比較 | |
---|---|---|---|---|---|
0 | 3 / 3 | 2 / 3 | 2 / 3 | 2 / 3 | 0,1 |
1 | 3 / 3 | 0 / 3 | 3 / 3 | 0 / 3 | 0,2 |
2 | 2 / 2 | 0 / 2 | 0 / 2 | 0 / 2 | 1,2 |
添加回答
舉報