python - 从列表python中提取数据
问题描述
我从 twitter 获得了 JSON 格式的多列数据。我正在与其中一个合作并尝试获取提到的用户的用户名并将它们放入单独的列中。
print(tweets_data['mentionedUsers'])
0 [{'username': 'HuntTerrorist', 'displayname': ...
1 [{'username': 'AttorneyCrump', 'displayname': ...
2 None
3 [{'username': 'realDonaldTrump', 'displayname'...
4 None
...
19995 None
19996 None
19997 None
19998 None
19999 None
Name: mentionedUsers, Length: 20000, dtype: object
我试过这段代码:
mentioned_users = []
for i in range(len(tweets_data)):
if tweets_data['mentionedUsers'][i]['username'] is not None:
mentioned_users.append(tweets_data['mentionedUsers'][i]['username'])
else:
mentioned_users.append(None)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-64-cc453018d33d> in <module>
3
4 for i in range(len(tweets_data)):
----> 5 if tweets_data['mentionedUsers'][i]['username'] is not None:
6 mentioned_users.append(tweets_data['mentionedUsers'][i]['username'])
7 else:
TypeError: list indices must be integers or slices, not str
谁能告诉我这有什么问题?我相信问题出在[]。如果是这样,我如何从列表中提取数据?谢谢你的帮助!
解决方案
更简单的方法是explode
列表,然后使用df['col_name'].apply(pd.Series)
假设您已经转换了您儿子的数据并将其存储在数据框 df 中。
exploded_df = df.explode('mentionedUsers')
user_df = exploded_df['mentionedUsers'].apply(pd.Series)
推荐阅读
- sql - 如何从一个表中选择另一个表中不存在于另一个表中的所有记录以用于另一个表中的某些条件?
- ansible - 在不知道键名的情况下遍历 Ansible 中的字典列表
- javascript - 传入对象作为道具反应
- mysql - 如何在sql中实现这一点?
- javascript - JavaScript - 改变对象字面量的值
- sharepoint - 使用 Power 自动将 PDF 文件从 Sharepoint 文件夹复制到 FTP
- javascript - 如何在反应中从地图中获取第一个值
- javascript - React 光滑的轮播项目变得模糊
- azure - Azure B2C:使用自定义声明查询 AAD?
- security - 金融科技公司所需的认证