python - 拆分列以修改数据框

标签 python pandas jupyter-notebook

我有一个数据框 df,其中有一列名为“属性”,如下所示

attributes
{"id":1,"firstname":"Joe","lastname":"Lee"}
{"id":12,"firstname":"Brian","lastname":"Li"}
{"id":2,"firstname":"Ron","lastname":"Stein"}

如何将此列拆分为不同的列,以便我的数据框现在看起来像 -

attributes                                     id    firstname  lastname
{"id":1,"firstname":"Joe","lastname":"Lee"}    1     Joe         Lee
{"id":12,"firstname":"Brian","lastname":"Li"}  12    Brian       Li
{"id":2,"firstname":"Ron","lastname":"Stein"}  2     Ron         Stein

我正在尝试访问每个值,如

df.attributes.id
df.attributes.firstname

可是我做不到!您的帮助将不胜感激。

最佳答案

你可以使用apply

In [98]: df.attributes.apply(pd.Series)
Out[98]:
  firstname  id lastname
0       Joe   1      Lee
1     Brian  12       Li
2       Ron   2    Stein

将结果加入原始 df

In [99]: df.join(df.attributes.apply(pd.Series))
Out[99]:
                                          attributes firstname  id lastname
0  {u'lastname': u'Lee', u'id': 1, u'firstname': ...       Joe   1      Lee
1  {u'lastname': u'Li', u'id': 12, u'firstname': ...     Brian  12       Li
2  {u'lastname': u'Stein', u'id': 2, u'firstname'...       Ron   2    Stein

In [100]: dff = df.join(df.attributes.apply(pd.Series))

访问名字

In [101]: dff.firstname
Out[101]:
0      Joe
1    Brian
2      Ron
Name: firstname, dtype: object

关于python - 拆分列以修改数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45357046/

相关文章:

python - 使用 PyGObject 获取 GDBusMenuModel 的菜单项

python - Scrapy:提取存储为脚本标签中文本的字典

python - 子进程 python filenotfounderror : [winerror 2]

python - 如何解决错误 : ModuleNotFoundError: No module named 'jupyterhub'

python - 查找列表的索引(如果它们超出特定值)。 python ,numpy

python - 如何修复: AttributeError:Class object has no attribute

python - 将数据帧与 "uneven"数据合并

python - 如何使用滚动汇总功能控制 pandas groupby 返回的索引

python - Pandas 文档操作 k 至 1000

python - IPython 代码从 Python 2 迁移到 Python 3