List of lists of lists to pandas dataframe

安稳与你 提交于 2019-12-11 04:08:16

问题


I have a list of lists of lists. The outer-most list is of length 20 (separate categories). The middle lists are of variable length (list of timestamps). The inner lists are of length 5 (splitting each timestamp). For example:

sTimestamps[0][:5][:] = 

[['Tue', 'Feb', '7', '10:06:30', '2017'],
 ['Tue', 'Feb', '7', '10:07:06', '2017'],
 ['Tue', 'Feb', '7', '10:07:40', '2017'],
 ['Tue', 'Feb', '7', '10:12:36', '2017'],
 ['Tue', 'Feb', '7', '10:13:24', '2017']]

I also have a list strings called categories of size 2 that contains the category names, where each index corresponds to the same index number for the outer-most list's 20 indices.

How can I convert this to a pandas dataframe, where the columns are the 5 components of the timestamp, plus a 6th additional column to designate the category name?

I could do this for a two-nested list, but this three-nested list is giving me difficulties.


回答1:


sTimeStamps = [
    [['Tue', 'Feb', '7', '10:06:30', '2017'],
     ['Tue', 'Feb', '7', '10:07:06', '2017'],
     ['Tue', 'Feb', '7', '10:07:40', '2017'],
     ['Tue', 'Feb', '7', '10:12:36', '2017'],
     ['Tue', 'Feb', '7', '10:13:24', '2017']],
    [['Tue', 'Feb', '7', '10:06:30', '2017'],
     ['Tue', 'Feb', '7', '10:07:06', '2017'],
     ['Tue', 'Feb', '7', '10:07:40', '2017']],
    ]

categories = ['cat%s' %i for i in range(20)]

pd.concat([pd.DataFrame(d) for d in sTimeStamps], keys=categories)

          0    1  2         3     4
cat0 0  Tue  Feb  7  10:06:30  2017
     1  Tue  Feb  7  10:07:06  2017
     2  Tue  Feb  7  10:07:40  2017
     3  Tue  Feb  7  10:12:36  2017
     4  Tue  Feb  7  10:13:24  2017
cat1 0  Tue  Feb  7  10:06:30  2017
     1  Tue  Feb  7  10:07:06  2017
     2  Tue  Feb  7  10:07:40  2017


来源:https://stackoverflow.com/questions/42868443/list-of-lists-of-lists-to-pandas-dataframe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!