[英]Convert a list of lists containing a dictionary to dataframe
I have the following output from a model I built我有以下 output 来自我构建的 model
test = [
[
{"label": "positive", "score": 0.005163147579878569},
{"label": "negative", "score": 0.0949820727109909},
{"label": "neutral", "score": 0.8998547792434692}
],
[
{"label": "positive", "score": 0.8533585667610168},
{"label": "negative", "score": 0.13094310462474823},
{"label": "neutral", "score": 0.01569831557571888}
],
[
{"label": "positive", "score": 0.007672784384340048},
{"label": "negative", "score": 0.9619094133377075},
{"label": "neutral", "score": 0.030417803674936295}
],
[
{"label": "positive", "score": 0.007140590343624353},
{"label": "negative", "score": 0.9494256973266602},
{"label": "neutral", "score": 0.04343372955918312}
]
]
I want to convert this output to a dataframe with columns positive, negative, neutral and rows their respective score.我想将此 output 转换为 dataframe 列,列正、负、中性和行各自的分数。 For example, for the first dictionary in my list of lists the desired output is:
例如,对于我的列表中的第一个字典,所需的 output 是:
Positive Negative Neutral
0.005163147579878569 0.0949820727109909 0.8998547792434692
I used the following function to convert it to a dataframe, but I can't set the label as columns and the score as rows我使用以下 function 将其转换为 dataframe,但我无法将 label 设置为列,并将分数设置为行
df = pd.DataFrame(test).stack().apply(pd.Series)
You could use a dictionary comprehension to get a more pandas friendly structure and then construct the dataframe:您可以使用字典理解来获得更友好的 pandas 结构,然后构造 dataframe:
pd.DataFrame(({d['label']:d['score'] for d in subl} for subl in test))
positive negative neutral
0 0.005163 0.094982 0.899855
1 0.853359 0.130943 0.015698
2 0.007673 0.961909 0.030418
3 0.007141 0.949426 0.043434
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.