首页 > 解决方案 > Python:字典列表到 pd 数据框(Twitter API)

问题描述

我使用 Twitter API 学术轨道收集了推文数据。其中一列是关于引用的推文唯一 ID 的字典列表,如下所示。

参考推文
1 [{'type': 'replied_to', 'id': '1212086431889313792'}]
2 [{'type': 'quoted', 'id': '1345063319540002817'}, {'type': 'replied_to', 'id': '1345066320761655296'}]
3 [{'type': '转推', 'id': '1344718164974833667'}, {'type': 'replied_to', 'id': '1211798476062908422'}]

我想像下面这样转换这些数据。

回复到 引用 转推
1 1212086431889313792
2 1345066320761655296 1345063319540002817
3 1211798476062908422 1344718164974833667

如果我使用“json_normalize”,则会导致错误消息(TypeError:字符串索引必须是整数)。我该如何使用 Python?

标签: pythonlistapidictionarytwitter

解决方案


这是一种方法(如果您需要解释代码,请告诉我):

def f(l):
    a={'replied_to':'', 'quoted':'', 'retweeted':''}
    x=pd.DataFrame(l)
    x=x.set_index('type')
    x=x.T
    x=x.reset_index(drop=True)
    x=x.to_dict(orient='records')
    a.update(x[0])
    return a

df['Referenced_tweets_2'] = [f(k) for k in df['Referenced_tweets']]

result = pd.DataFrame.from_dict(df['Referenced_tweets_2'].to_list())
    
print(result)

输出:

            replied_to               quoted            retweeted
0  1212086431889313792
1  1345066320761655296  1345063319540002817
2  1211798476062908422                       1344718164974833667

推荐阅读