I need to make a "perfect tree"-like from pandas dataframe based on values in dataframe

Viewed 28

I have a dataframe like this:

   name1 name2  name3 
0    1     2     3
1    1     2     1
2    1     3     4

How can I transform it to like this:

   name1 name2  name3 
0    1     2     1
0    1     2     3
0    1     2     4
2    1     3     1
2    1     3     3
2    1     3     4

If we look at tree representation:

                       1
                      /  \
                     /    \
                    /      \
                   /        \
                  2          3   
                 /|\        /|\
                / | \      / | \
               1  3  4    1  3  4

I have a solution but it's very long and primitive, all about append and repeat, my question is, is there a built-in function that can do what I'm asking, or maybe a suggestion for a short code solution?

1 Answers

IIUC, you can use itertools.product:

from itertools import product
df2 = pd.DataFrame(
         product(*(set(s) for _,s in df.iteritems())),
         columns=df.columns
       )

print(df2)

Alternative with a cross merge:

df2 = (df[['name1', 'name2']].drop_duplicates()
       .merge(df[['name3']].drop_duplicates(), how='cross')
      )

output:

   name1  name2  name3
0      1      2      1
1      1      2      3
2      1      2      4
3      1      3      1
4      1      3      3
5      1      3      4
Related