最近,我在Python中使用Oracle的AI语言API进行了情感分析。我让API迭代了1300条Tweets,并将API的输出存储在一个列表中,其中列表中的每个元素对应于一个Tweet ID。然后我创建了一个字典,其中键是Tweet ID,值是该Tweet ID的API输出。我现在有了一个包含字典的大量字典,并且不确定如何将它转换为Pandas中的数据格式。
这是我正在使用的字典的前几个词条。
{1292750633104289792: {
"aspects": []
},
1275918779831238656: {
"aspects": []
},
1293251961031204865: {
"aspects": [
{
"length": 8,
"offset": 51,
"scores": {
"Negative": 0.18023298680782318,
"Neutral": 0.0,
"Positive": 0.8197670578956604
},
"sentiment": "Positive",
"text": "building"
}
]
},
1293312774563606531: {
"aspects": []
},
1293375754751881217: {
"aspects": [
{
"length": 4,
"offset": 5,
"scores": {
"Negative": 0.9987309575080872,
"Neutral": 0.0012690634466707706,
"Positive": 0.0
},
"sentiment": "Negative",
"text": "poll"
}
]
}}
提前谢了。
发布于 2021-12-08 13:57:18
您可以使用嵌套理解将结构扁平,然后将结果传递给pd.DataFrame
。
import pandas as pd
r = [{'tweet_id':a,
'length':i['length'],
'offset':i['offset'],
**{f'score_{j}':k for j, k in i['scores'].items()},
'sentiment':i['sentiment'],
'text':i['text'],
}
for a, b in data.items() for i in (b['aspects'] if isinstance(b, dict) else b.aspects)]
df = pd.DataFrame(r)
输出:
tweet_id length offset score_Negative score_Neutral score_Positive sentiment text
0 1293251961031204865 8 51 0.180233 0.000000 0.819767 Positive building
1 1293375754751881217 4 5 0.998731 0.001269 0.000000 Negative poll
https://stackoverflow.com/questions/70282151
复制相似问题