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

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

使用 Python 創建數字組合并計算不同組合的數量

使用 Python 創建數字組合并計算不同組合的數量

阿波羅的戰車 2023-03-30 09:54:38
我有 df1,它包含一組特定的 ID 作為列,而 df2 在每一行中包含 ID 的混合(如下圖所示)。我想創建一個數據框,其中包含 df1 中存在于 df2 的每一行中的所有不同 ID 組合,并獲取所有不同組合的計數。df1=pd.DataFrame({'Id':["181","456","235","653","987","5","300"]})df2=pd.DataFrame({'Tag Id':["213,435,181,954,987","456","215,435,181,754,987","213,12,432,300,653,987"})
查看完整描述

2 回答

?
慕森卡

TA貢獻1806條經驗 獲得超8個贊

這是使用列表理解和 itertools 的更快方法 -


import itertools


#Get vocab of items

vocab = list(df1['Id'].astype(int)) 


#get filtered list of combinations in each row of df2

filtered = [[int(j) for j in i.split(',') if int(j) in vocab] for i in list(df2['Tag Id'])]


#Get counts of the combinations and display as a dataframe 

counts = list(zip(*np.unique(filtered, return_counts=True)))

pd.DataFrame(counts, columns=['Combinations', 'Counts'])


    Combinations    Counts

0   [181, 987]      2

1   [300, 653, 987] 1

2   [456]           1


查看完整回答
反對 回復 2023-03-30
?
江戶川亂折騰

TA貢獻1851條經驗 獲得超5個贊

讓我們嘗試將inexplode分開,然后用和計數:Tag Idsdf1mergedf1


s = (df2['Tag Id'].str.split(',')

         .explode()

         .reset_index()

    )


(df1.merge(s, left_on='Id', right_on='Tag Id')

    .sort_values('Tag Id')

    .groupby('index')

    .agg(Combination=('Id',','.join))

    ['Combination']

    .value_counts().reset_index()

)

輸出:


         index  Combination

0      181,987            2

1  653,987,300            1

2          456            1


查看完整回答
反對 回復 2023-03-30
  • 2 回答
  • 0 關注
  • 150 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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