TL;DR 如果 Pandas DataFrame 中加载的字段本身包含 JSON 文档,如何以类似 Pandas 的方式使用它们?
目前,我将 Twitter 库 (twython) 中的 json/字典结果直接转储到 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))
这就像魔术一样:
我希望能够修改“状态”字段 Pandas 样式(直接访问属性)。有什么办法吗?
编辑:类似于 df['status:text']。状态具有诸如“文本”、“已创建_at”之类的字段。一种选择是展平/规范化这个 json 字段,如 this pull request 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
在某些情况下,您会想要 concat这个到 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
如果它更深入,你可以这样做几次......
关于python - 如何访问 Pandas DataFrame 中嵌入的 json 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18665284/