All possible combinations of pandas data frame rows

杀马特。学长 韩版系。学妹 提交于 2019-12-23 03:47:54

问题


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

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

and so on.....


回答1:


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')

The output will be:

  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   


来源:https://stackoverflow.com/questions/51746635/all-possible-combinations-of-pandas-data-frame-rows

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!