TL; DR如果Pandas DataFrame中加载的字段本身包含JSON文档,如何以类似Pandas的方式使用它们?
目前,我直接将Twitter库(twython)中的json / dictionary结果转储到Mongo集合中(在此称为用户)。
from twython import Twython
from pymongo import MongoClient
tw = Twython(...<auth>...)
# Using mongo as object storage
client = MongoClient()
db = client.twitter
user_coll = db.users
user_batch = ... # collection of user ids
user_dict_batch = tw.lookup_user(user_id=user_batch)
for user_dict in user_dict_batch:
if(user_coll.find_one({"id":user_dict['id']}) == None):
user_coll.insert(user_dict)
填充此数据库后,我将文档读入Pandas:
# Pull straight from mongo to pandas
cursor = user_coll.find()
df = pandas.DataFrame(list(cursor))
像魔术一样工作:
我希望能够处理“状态”字段中的熊猫样式(直接访问属性)。有办法吗?
编辑:类似df ['status:text']。状态具有“文本”,“ created_at”之类的字段。一种选择可能是扁平化/标准化此json字段,例如Wes McKinney正在处理的拉取请求。
一种解决方案是使用Series构造函数粉碎它:
In [1]: df = pd.DataFrame([[1, {'a': 2}], [2, {'a': 1, 'b': 3}]])
In [2]: df
Out[2]:
0 1
0 1 {u'a': 2}
1 2 {u'a': 1, u'b': 3}
In [3]: df[1].apply(pd.Series)
Out[3]:
a b
0 2 NaN
1 1 3
在某些情况下,您需要将其连接到DataFrame而不是dict行:
In [4]: dict_col = df.pop(1) # here 1 is the column name
In [5]: pd.concat([df, dict_col.apply(pd.Series)], axis=1)
Out[5]:
0 a b
0 1 2 NaN
1 2 1 3
如果更深入,您可以执行几次...
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句