pandas 数据框行的所有可能组合 [英] All possible combinations of pandas data frame rows

查看:49
本文介绍了 pandas 数据框行的所有可能组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含4行的pandas数据框:

I have a pandas data frame having 4 rows:

df:

col1    col2    col3    col4
A1      A2      A3      A4
B1      B2      B3      B4 
C1      C2      C3      C4
D1      D2      D3      D4

我如何找到选择此数据帧两行的所有可能组合.在这种情况下,我可以采用4C2 = 6种可能的方式从4行中选择2行

How do i find all possible combinations of selecting two rows of this data frame. In this case I can choose 2 rows from 4 rows in 4C2 = 6 possible ways

df1:

col1    col2    col3    col4
A1      A2      A3      A4
B1      B2      B3      B4

df2:

col1    col2    col3    col4
A1      A2      A3      A4
C1      C2      C3      C4

df3:

col1    col2    col3    col4
A1      A2      A3      A4
D1      D2      D3      D4

以此类推.....

推荐答案

首先,您需要使用itertools查找所有组合,然后使用

First, you need to find all the combinations using itertoolsand then use the output of combinations as index to your dataframe. You will get all the possible dataframes of the given number of rows.

from itertools import combinations
for index in list(combinations(df.index,2)):
    print(df.loc[index,:])
    print('\n')

输出将是:

  col1 col2 col3 col4
0   A1   A2   A3   A4
1   B1   B2   B3   B4


  col1 col2 col3 col4
0   A1   A2   A3   A4
2   C1   C2   C3   C4


  col1 col2 col3 col4
0   A1   A2   A3   A4
3   D1   D2   D3   D4


  col1 col2 col3 col4
1   B1   B2   B3   B4
2   C1   C2   C3   C4


  col1 col2 col3 col4
1   B1   B2   B3   B4
3   D1   D2   D3   D4


  col1 col2 col3 col4
2   C1   C2   C3   C4
3   D1   D2   D3   D4   

这篇关于 pandas 数据框行的所有可能组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆