Nic
Nic

Reputation: 3507

create a dataframe from a list of length-unequal lists

I try to convert such a list:

l = [[1, 2, 3, 17], [4, 19], [5]]

to a dataframe having each of the number as indice, and position of list as value.

For example, 19 is in the second list, I thus expect to get somwhere one row with "19" as index and "1" as value, and so on.

I managed to get it (cf.boiler plate below), but I guess there is something more simple

>>> df=pd.DataFrame(l)    
>>> df=df.unstack().reset_index(level=0,drop=True)    
>>> df=df[df.notnull()==True]   # remove NaN rows 
>>> df=pd.DataFrame(df)    
>>> df = df.reset_index().set_index(0)    
>>> print df
    index
0        
1       0
4       1
5       2
2       0
19      1
3       0
17      0

Thanks in advance.

Upvotes: 3

Views: 1926

Answers (1)

unutbu
unutbu

Reputation: 879611

In [52]: pd.DataFrame([(item, i) for i, seq in enumerate(l) 
                       for item in seq]).set_index(0)
Out[52]: 
    1
0    
1   0
2   0
3   0
17  0
4   1
19  1
5   2

Upvotes: 3

Related Questions