亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在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 關注
  • 109 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號