List of LISTS of tuples to Pandas dataframe?

前端 未结 4 1937
花落未央
花落未央 2021-01-13 09:39

I have a list of lists of tuples, where every tuple is of equal length, and I need to convert the tuples to a Pandas dataframe in such a way that the columns of the datafram

4条回答
  •  感动是毒
    2021-01-13 10:04

    You can do it like this :D

    tupList = [[('commentID', 'commentText', 'date'), ('123456', 'blahblahblah', '2019')], [('45678', 'hello world', '2018'), ('0', 'text', '2017')]]
    
    # Trying list comprehension from previous stack question:
    df = pd.DataFrame([[y for y in x] for x in tupList])
    df_1 = df[0].apply(pd.Series).assign(index= range(0, df.shape[0]*2, 2)).set_index("index")
    df_2 = df[1].apply(pd.Series).assign(index= range(1, df.shape[0]*2, 2)).set_index("index")
    
    pd.concat([df_1, df_2], axis=0).sort_index()
    

提交回复
热议问题