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

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

如何在數據框中使用 itertools 組合

如何在數據框中使用 itertools 組合

慕絲7291255 2021-11-02 20:06:25
我有一個像這樣有 4 列的數據框Asset1 Asset2 Asset3 Asset4  a      b      c      d   e      f      g      h  我想創建一個列,itertools.combinations用于為我提供獨特組合的結果,因此理想情況下輸出將是:  Asset1 Asset2 Asset3 Asset4   test  a      b      c      d        [abc, abd, bcd, acd]  e      f      g      h        [efg, efh, egh, fgh]我嘗試使用.join()和組合但不起作用。有任何想法嗎?
查看完整描述

1 回答

?
慕森卡

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

歡迎來到 SO!


我建議使用lambdarow-wise ( axis=1):


from itertools import combinations

import pandas as pd


df = pd.DataFrame({'Asset1':('a','e'), 'Asset2': ('b','f'), 'Asset3': ('c', 'g'),  'Asset4': ('d', 'h')})

df['combinations'] = df.apply(lambda r: list(combinations(r, 3)), axis=1)


print(df)

輸出:


  Asset1                      ...                                                       combinations

0      a                      ...                       [(a, b, c), (a, b, d), (a, c, d), (b, c, d)]

1      e                      ...                       [(e, f, g), (e, f, h), (e, g, h), (f, g, h)]


[2 rows x 5 columns]

list(combinations...如果您稍后只迭代組合,您也可以跳過- 這樣您將節省一些內存并將計算延遲到訪問的時刻df['combinations']:


df['combinations'] = df.apply(lambda r: combinations(r, 3), axis=1)

print(df)

然后你會在combinations列中得到一個非常神秘的對象:


  Asset1                        ...                                                               combinations

0      a                        ...                          <itertools.combinations object at 0x0000022392...

1      e                        ...                          <itertools.combinations object at 0x0000022392...


[2 rows x 5 columns]


查看完整回答
反對 回復 2021-11-02
  • 1 回答
  • 0 關注
  • 176 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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