【问题标题】:How do I access embedded json objects in a Pandas DataFrame?如何访问 Pandas DataFrame 中嵌入的 json 对象?
【发布时间】:2013-09-10 23:55:56
【问题描述】:

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 正在研究。

【问题讨论】:

  • 你能举一个你真正想做的例子吗?您展示了df['status'] 列,但您想用它做什么?
  • FWIW 有一个 PR 正在为此工作:github.com/pydata/pandas/pull/4007
  • df.status的元素中是否有嵌套记录?
  • @BrenBarn - 我希望能够在这些字段中进行选择,有点像 df[df['status']['favorited'] == False]。
  • @PhillipCloud - 很高兴看到公关!此外,看起来其他人在本期中使用 Twitter API 做同样类型的事情:github.com/pydata/pandas/issues/1067

标签: python json mongodb twitter pandas


【解决方案1】:

一种解决方案就是使用 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 this 发送到 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

如果它更深入,你可以这样做几次......

【讨论】:

  • 拉德。只要没有空条目,这效果很好。
  • 还需要合并状态,添加后缀,以便名称冲突得到体面的名称。 df2 = df[df.status.notnull()] statuses = df2.status.apply(pandas.Series) df2 = df2.merge(statuses, left_index=True, right_index=True,suffixes=("","_status") )
  • 哦,那也可以,但在这种情况下我不需要空结果。
猜你喜欢
  • 2019-09-15
  • 2018-01-23
  • 2022-01-11
  • 2016-03-04
  • 1970-01-01
  • 2022-01-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多