1

I have a panda dataframe like this:

      id  t     value      nodes  sup
1      0  2  0.032396     [1, 2]    0
10     3  2  0.060529  [1, 2, 3]    0

and I would like to explode it to all possible powersets of the column nodes:

      id  t     value      nodes  sup
1      0  2  0.032396        [1]    0
10     3  2  0.060529        [1]    0
1      0  2  0.032396        [2]    0
10     3  2  0.060529        [2]    0
10     3  2  0.060529        [3]    0
1      0  2  0.032396      [1,2]    0
10     3  2  0.060529      [1,2]    0
10     3  2  0.060529    [1,2,3]    0

I am aware of the explode method. but is there any suggestions on how to perform the above transformation?

sos
  • 305
  • 1
  • 9

1 Answers1

2

With help from this answer:

from itertools import chain, combinations


def powerset(iterable):
    "powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"
    s = list(iterable)
    return chain.from_iterable(combinations(s, r) for r in range(len(s) + 1))


df.nodes = df.nodes.apply(lambda x: [list(p) for p in powerset(x) if p])
df = df.explode("nodes")
print(df)

Prints:

    id  t     value      nodes  sup
1    0  2  0.032396        [1]    0
1    0  2  0.032396        [2]    0
1    0  2  0.032396     [1, 2]    0
10   3  2  0.060529        [1]    0
10   3  2  0.060529        [2]    0
10   3  2  0.060529        [3]    0
10   3  2  0.060529     [1, 2]    0
10   3  2  0.060529     [1, 3]    0
10   3  2  0.060529     [2, 3]    0
10   3  2  0.060529  [1, 2, 3]    0
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91