我正在将Twitter数据(推文+元数据)收集到MongoDB服务器中。现在我想进行一些统计分析。为了将数据从MongoDB获取到Pandas数据框架中,我使用了以下代码:
cursor = collection.find({},{'id': 1, 'text': 1})
tweet_fields = ['id', 'text']
result = pd.DataFrame(list(cursor), columns = tweet_fields)
我成功地将数据加载到 Pandas 中,这太好了。现在我想对创建推文的用户进行一些分析,这也是我收集的数据。这些数据位于 JSON 的嵌套部分中(我不确定这是否是真正的 JSON),例如 user.id,它是 Twitter 用户帐户的 ID。
我只需使用点符号将其添加到游标中:
cursor = collection.find({},{'id': 1, 'text': 1, 'user.id': 1})
但是这会导致该列的值为 NaN。我发现问题出在数据结构上:
没有包含 user.id 的游标位。
[{'_id': ObjectId('561547ae5371c0637f57769e'),
'id': 651795711403683840,
'text': 'Video: Zuuuu gut! Caro Korneli besucht für extra 3 Pegida Via KFMW http://t.co/BJX5GKrp7s'},
{'_id': ObjectId('561547bf5371c0637f5776ac'),
'id': 651795781557583872,
'text': 'Iets voor werkloze xenofobe PVV-ers, (en dat zijn waarschijnlijk wel de meeste).........Ze zoeken bij Frontex een paar honderd grenswachten.'},
{'_id': ObjectId('561547ab5371c0637f57769c'),
'id': 651795699881889792,
'text': 'RT @ansichtssache47: Geht gefälligst arbeiten, die #Flüchtlinge haben Hunger! http://t.co/QxUYfFjZB5 #grenzendicht #rente #ZivilerUngehorsa…'}]
使用user.id位的光标位。
[{'_id': ObjectId('561547ae5371c0637f57769e'),
'id': 651795711403683840,
'text': 'Video: Zuuuu gut! Caro Korneli besucht für extra 3 Pegida Via KFMW http://t.co/BJX5GKrp7s',
'user': {'id': 223528499}},
{'_id': ObjectId('561547bf5371c0637f5776ac'),
'id': 651795781557583872,
'text': 'Iets voor werkloze xenofobe PVV-ers, (en dat zijn waarschijnlijk wel de meeste).........Ze zoeken bij Frontex een paar honderd grenswachten.',
'user': {'id': 3544739837}}]
简而言之,我不明白如何将收集的数据中的嵌套部分放入Pandas数据框的单独列中。
x
中。clean_df = mongo_to_dataframe(x)
将为您提供一个未嵌套的mongo数据的数据帧(dataframe)在clean_df
中。 - metersk