Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List of tuples into a binary table?

I have a list of transactions/tuples in Python with varying number or elements, like this:

lst = [('apple','banana','carrots'),('apple',),('banana','carrots',)]

I would like to store this list in a tabular form (preferably in a pd.DataFrame) such as this:

   apple  banana  carrots
0      1       1        1
1      1       0        0
2      0       1        1

But if try to convert directly using pd.DataFrame, I get his instead:

pd.DataFrame(lst)
        0        1        2
0   apple   banana  carrots
1   apple     None     None
2  banana  carrots     None

How can I convert this type of list into a binary table?

like image 965
Adriano Arantes Avatar asked Dec 13 '17 00:12

Adriano Arantes


1 Answers

This is very simple if you use value_counts over columns i.e

pd.DataFrame(lst).apply(pd.value_counts,1).fillna(0)

    apple  banana  carrots
0    1.0     1.0      1.0
1    1.0     0.0      0.0
2    0.0     1.0      1.0
like image 80
Bharath Avatar answered Sep 20 '22 03:09

Bharath