3

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.

Nic
  • 3,365
  • 3
  • 20
  • 31

1 Answers1

3
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
unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677