简体   繁体   English

列表列表转换为 pandas DataFrame

[英]List of lists conversion to pandas DataFrame

I have a list of lists that looks like this:我有一个看起来像这样的列表:

[[('category', 'evaluation'), ('polarity', 'pos'), ('strength', '1'), ('type', 'good')],
[('category', 'intensifier'), ('type', 'shifter')],
[('category', 'evaluation'), ('polarity', 'pos'), ('strength', '2'), ('type', 'good')],

Note that not all lists contain all the attributes.请注意,并非所有列表都包含所有属性。

I would like, if possible, to convert this to a DataFrame, where each list represents a new row and the names of the columns would be given by the first element (eg 'category' , 'polarity' , 'strength' , 'type' ).如果可能的话,我想将其转换为 DataFrame,其中每个列表代表一个新行,列的名称将由第一个元素给出(例如'category''polarity''strength''type ' )。 In the end, the DataFrame should look like this:最后,DataFrame 应该是这样的:

           category     polarity     strength     type
df[0]:    evaluation      pos           1         good
df[1]:    intensifier     NaN          NaN       shifter
df[2]:    evaluation      pos           2         good

Any help would be greatly appreciated.任何帮助将不胜感激。

You could transform each list into a dictionary:您可以将每个列表转换为字典:

import pandas as pd

data = [[('category', 'evaluation'), ('polarity', 'pos'), ('strength', '1'), ('type', 'good')],
[('category', 'intensifier'), ('type', 'shifter')],
[('category', 'evaluation'), ('polarity', 'pos'), ('strength', '2'), ('type', 'good')]]

df = pd.DataFrame(data=[dict(e) for e in data])

print(df)

Output Output

      category polarity strength     type
0   evaluation      pos        1     good
1  intensifier      NaN      NaN  shifter
2   evaluation      pos        2     good

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM