Home > Back-end >  All possible combinations of columns and rows in pandas DataFrame
All possible combinations of columns and rows in pandas DataFrame

Time:11-18

I have this Dataframe that I want to get all possible combinations of this dataframe across both rows and columns.

A_Points B_Points C_Points
0 1 1
3 5 4
9 2 4

For example a combination as follows Points = 0 5 4, or 9 1 1. Is there a builtin tool for such problem?

This is what I tried, but it did not give the desired output.

> import itertools
> combined_dataframe = pd.DataFrame({'{}{}'.format(a, b): possible_feature_characteristicpoints[a] - possible_feature_characteristicpoints[b] for a, b in itertools.combinations(possible_feature_characteristicpoints.columns, 2)})

CodePudding user response:

Use itertools.product and sum:

from itertools import product

out = list(map(sum, product(*df.to_numpy().tolist())))

Output:

[12, 5, 7, 14, 7, 9, 13, 6, 8, 13, 6, 8, 15, 8, 10, 14, 7, 9, 13, 6, 8, 15, 8, 10, 14, 7, 9]

Intermediate:

list(product(*df.to_numpy().tolist()))

Output:

[(0, 3, 9),
 (0, 3, 2),
 (0, 3, 4),
 (0, 5, 9),
 (0, 5, 2),
 (0, 5, 4),
 ...
 (1, 4, 2),
 (1, 4, 4)]

CodePudding user response:

Another way with list comprehension,

import pandas as pd
data = {
  "A_Points": [0,3,9],
  "B_Points": [1,5,2],
  "C_Points": [1,4,4],
}

df = pd.DataFrame(data)
result = [ (i, j, k)
    for i in df.A_Points
    for j in df.B_Points
    for k in df.C_Points
]
print(result)

Output:

[(0, 1, 1), (0, 1, 4), (0, 1, 4), (0, 5, 1), (0, 5, 4), (0, 5, 4), (0, 2, 1), (0, 2, 4), (0, 2, 4), (3, 1, 1), (3, 1, 4), (3, 1, 4), (3, 5, 1), (3, 5, 4), (3, 5, 4), (3, 2, 1), (3, 2, 4), (3, 2, 4), (9, 1, 1), (9, 1, 4), (9, 1, 4), (9, 5, 1), (9, 5, 4), (9, 5, 4), (9, 2, 1), (9, 2, 4), (9, 2, 4)]
  • Related