我有一个数据框 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/