猿问

如何在数据框中使用 itertools 组合

我有一个像这样有 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()和组合但不起作用。有任何想法吗?


慕丝7291255
浏览 163回答 1
1回答

慕森卡

欢迎来到 SO!我建议使用lambdarow-wise ( axis=1):from itertools import combinationsimport pandas as pddf = pd.DataFrame({'Asset1':('a','e'), 'Asset2': ('b','f'), 'Asset3': ('c', 'g'),&nbsp; 'Asset4': ('d', 'h')})df['combinations'] = df.apply(lambda r: list(combinations(r, 3)), axis=1)print(df)输出:&nbsp; Asset1&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ...&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;combinations0&nbsp; &nbsp; &nbsp; a&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ...&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;[(a, b, c), (a, b, d), (a, c, d), (b, c, d)]1&nbsp; &nbsp; &nbsp; e&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ...&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;[(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列中得到一个非常神秘的对象:&nbsp; Asset1&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ...&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;combinations0&nbsp; &nbsp; &nbsp; a&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ...&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <itertools.combinations object at 0x0000022392...1&nbsp; &nbsp; &nbsp; e&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ...&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <itertools.combinations object at 0x0000022392...[2 rows x 5 columns]
随时随地看视频慕课网APP

相关分类

Python
我要回答