将列表中的索引附加到列表列表以创建 pandas df

我想知道是否可以从列表列表创建数据框,其中 index_list 中的每个项目都作为索引附加到 lst 中的每个值:


index_list = ['phase1', 'phase2', 'phase3']

lst = [['a', 'b', 'c'], ['d', 'e', 'f', 'g'], ['h', 'i', 'j']]

http://img1.mukewang.com/63b4e4040001299201300176.jpg

感谢您的任何帮助!!

编辑:内部列表的大小不一定相同。


明月笑刀无情
浏览 131回答 2
2回答

料青山看我应如是

你可以pd.Series.explode在这里使用。pd.Series(lst,index=index_list).explode() phase1    a phase1    b phase1    c phase2    d phase2    e phase2    f phase2    g phase3    h phase3    i phase3    j dtype: object另一种解决方案使用np.repeat和np.concatenater_len = [len(r) for r in lst] pd.Series(np.concatenate(lst), index=np.repeat(index_list,r_len)) phase1    a phase1    b phase1    c phase2    d phase2    e phase2    f phase2    g phase3    h phase3    i phase3    j dtype: object时间结果:In [501]: %%timeit      ...: pd.Series(lst,index=index_list).explode()      ...:      ...:363 µs ± 16.5 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) In [503]: %%timeit      ...: r_len = [len(r) for r in lst]      ...: pd.Series(np.concatenate(lst), index=np.repeat(index_list,r_len))      ...:      ...:      236 µs ± 17.8 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

沧海一幻觉

这个问题看起来类似于 R 的函数,并且在pandas cookbook(页面底部)中expand.grid()列出。此函数允许您使用给定输入值的所有组合创建数据框。首先定义一个函数:def expand_grid(data_dict):rows = itertools.product(*data_dict.values())return pd.DataFrame.from_records(rows, columns=data_dict.keys())然后你可以像这样使用它:df = expand_grid({'index': ['phase1', 'phase2', 'phase3'],'Col1': [['a', 'b', 'c'], ['d', 'e', 'f', 'g'], ['h', 'i', 'j']]})
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python