python - 如何将嵌套的字典列表展平为多行?

标签 python python-3.x pandas nested

我在 pandas 数据框中有一列,如下所示:

col1         list_of_dictionaries
1           [{'id': 1,'tid': 1,'measure': 'time','i_id': 0,'type': 'time','time': '2000-06-19T05:08:11Z'},{'id': 2,'tid': 2,'measure': 'time','i_id': 1,'type': 'time','time': '2000-06-19T05:08:11Z'},{'id': 3,'tid': 3,'measure': 'time','i_id': 2,'type': 'time','time': '2000-06-19T05:08:11Z'},{'id': 4,'tid': 4,'measure': 'time','i_id': 1,'type': 'time','time': '2000-06-19T05:08:11Z','status': {'calendar': 0, 'business': 0}}]

如何展平同一数据框中的字典列表,使其看起来像这样?

col1    id   tid   measure i_id  type    time                 status.calendar     status.business                
1       1    1      time    0     time   2000-06-19T05:08:11Z    0                         0  
1       2    2      time    1     time   2000-06-19T05:08:11Z    0                         0
1       3    3      time    2     time   2000-06-19T05:08:11Z    0                         0
1       4    4      time    1     time   2000-06-19T05:08:11Z    0                         0

我想保留原始数据并在其中扩展,同时每次重复列名时创建更多行。

我在列上尝试了 json_normalize 但出现错误:

AttributeError: 'str' object has no attribute 'values'

编辑:

x is a tuple according to spyder:

[
{
'
i
d
'
:

最佳答案

您可以在纯Python中取消嵌套,然后使用json_normalize

ids, x = zip(*[(id_, value) for id_, sub in zip(df['col1'], df.lod.values.tolist())\
                            for value in sub])
ndf = pd.io.json.json_normalize(x)

关于python - 如何将嵌套的字典列表展平为多行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57189159/

相关文章:

python - 保存时 Pandas 的身材正在被削减

对象上的 Python itertools 组合

python - 打开 putty 窗口并运行 ssh 命令 - Python

python - 如何使用 tweepy/Python 在 Twitter 上关注某人?

python - 在 Pandas str.contains() 中使用正则表达式中的变量

python - 突出显示超过一周的日期单元格!破折号

python - Flask-安全访问登录管理器

python - 使用 asyncore 读取套接字缓冲区

python - 是否可以在不定义函数的情况下实现这一目标?

python - "Risk"骰子游戏列表索引错误