简体   繁体   English

熊猫数据框行的所有可能组合

[英]All possible combinations of pandas data frame rows

I have a pandas data frame having 4 rows: 我有一个具有4行的pandas数据框:

df: 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 在这种情况下,我可以4C2从4行中选择2行= 6种可能的方式

df1: df1:

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

df2: df2:

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

df3: df3:

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

and so on..... 等等.....

First, you need to find all the combinations using itertools and then use the output of combinations as index to your dataframe. 首先,您需要使用itertools查找所有组合,然后将combinations的输出用作数据框的索引。 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   

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 熊猫:所有可能的行组合 - Pandas: all possible combinations of rows pandas DataFrame 中所有可能的列和行的组合 - All possible combinations of columns and rows in pandas DataFrame 如何创建循环或 function 以提供 Python Pandas 中数据帧中所有可能的数据组合? - How to create loop or function which give all possible combinations of data from Data Frame in Python Pandas? 从未涵盖所有可能组合的数据创建计数表,但熊猫数据框中提供了缺失值 - Creating a counting table from data that is not cover all possible combinations and missing value is available in pandas data frame 在 pandas 数据框中的两列组合的行之间填充 - fill in between rows of two column combinations in a pandas data frame 查找熊猫数据框列的所有唯一组合 - Finding all unique combinations of columns of pandas data frame 将 pandas 数据帧转换为具有所有组合的字典 - Converting pandas data-frame into a dictionary with all combinations 动态创建熊猫数据框中的所有列组合 - Dynamically create all column combinations in a pandas data frame 在 Pandas 数据框中删除全为零的行 - Drop rows with all zeros in pandas data frame 计算熊猫数据框中唯一组合的数量 - count the number of unique combinations in pandas data frame
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM