首页 > 解决方案 > 从列表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

谁能告诉我这有什么问题?我相信问题出在[]。如果是这样,我如何从列表中提取数据?谢谢你的帮助!

标签: pythonpandasdataframefor-loopextract

解决方案


更简单的方法是explode列表,然后使用df['col_name'].apply(pd.Series)

假设您已经转换了您儿子的数据并将其存储在数据框 df 中。


exploded_df = df.explode('mentionedUsers')

user_df = exploded_df['mentionedUsers'].apply(pd.Series)


推荐阅读