Python 列表转换为数据帧的列表列表
我有一个列表,如下所示:Python 列表转换为数据帧的列表列表,python,pandas,list,dataframe,Python,Pandas,List,Dataframe,我有一个列表,如下所示: [[('category', 'evaluation'), ('polarity', 'pos'), ('strength', '1'), ('type', 'good')], [('category', 'intensifier'), ('type', 'shifter')], [('category', 'evaluation'), ('polarity', 'pos'), ('strength', '2'), ('type', 'good')],
[[('category', 'evaluation'), ('polarity', 'pos'), ('strength', '1'), ('type', 'good')],
[('category', 'intensifier'), ('type', 'shifter')],
[('category', 'evaluation'), ('polarity', 'pos'), ('strength', '2'), ('type', 'good')],
category polarity strength type
df[0]: evaluation pos 1 good
df[1]: intensifier NaN NaN shifter
df[2]: evaluation pos 2 good
请注意,并非所有列表都包含所有属性
如果可能的话,我想将其转换为数据帧,其中每个列表代表一个新行,列的名称由第一个元素给出,例如“category”、“polarity”、“strength”、“type”。最后,数据帧应该如下所示:
[[('category', 'evaluation'), ('polarity', 'pos'), ('strength', '1'), ('type', 'good')],
[('category', 'intensifier'), ('type', 'shifter')],
[('category', 'evaluation'), ('polarity', 'pos'), ('strength', '2'), ('type', 'good')],
category polarity strength type
df[0]: evaluation pos 1 good
df[1]: intensifier NaN NaN shifter
df[2]: evaluation pos 2 good
任何帮助都将不胜感激 您可以将每个列表转换为字典:
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)
输出
您可以将每个列表转换为字典:
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)
输出
正是我需要的。谢谢大家!@帕特里很高兴我能帮上忙!正是我需要的。谢谢大家!@帕特里很高兴我能帮上忙!