python - 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?
解决方案
这是一种方法(如果您需要解释代码,请告诉我):
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
推荐阅读
- c# - 为什么这个调用对于编译器来说是模棱两可的?
- spring - 为什么在其他测试类上需要 DirtiesContext 来模拟具有 JMS 侦听器的类的 bean 依赖关系
- paypal - 我如何处理 PayPal 公钥?
- sql - 使用2个条件访问前N个的sql移动平均值
- python-3.x - 通过重复获得不同的数字集
- html - 如何仅使用 HTML/CSS 将可折叠内容居中在表格行下?
- java - 选择帐户时不会出现 Google 注册弹出窗口
- reactjs - 向 ReactJS Google Map 添加自定义样式的问题
- javascript - 电子锻造与反应?
- python - 编写自定义装饰器以检查会话在 Django 中是否处于活动状态