从长度不等的列表中创建一个数据框 [英] 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.
例如,第二个列表中有19,因此我希望在某处以"19"作为索引并以"1"作为值,以此类推.
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
谢谢.
推荐答案
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
这篇关于从长度不等的列表中创建一个数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文