python - 从 Pandas 列中提取嵌套字典

标签 python pandas

我尝试从 pandas 数据框中的嵌套字典创建一个数据框,但我无法使其工作......

我的数据框:

    created_at                  selected
    2019-08-13T12:24:53+00:00   {"982813":false,"1786112":true,"3002218":false}
    2019-08-31T13:47:51+00:00   {"309279":true,"1903384":false}
        ...

我想使用选定的列数据创建一个新的 df,格式如下:

        created_at                  ID            Value
        2019-08-13T12:24:53+00:00   982813        false    
        2019-08-13T12:24:53+00:00   1786112       true
        2019-08-13T12:24:53+00:00   3002218       false
        2019-08-31T13:47:51+00:00   309279        true
        2019-08-31T13:47:51+00:00   1903384       false
        ...

我一直在尝试使用explode()和json_normalize()但没有成功,所以我决定使用pd.DataFrame.from_dict()和for循环,如下所示,但我收到了错误。

x = {}
for row in df.selected:
    pd.DataFrame.from_dict(row, orient='index')

但我收到以下错误:

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

我仍然是Python的初学者,所以如果有人提出想法/解释,我会洗耳恭听。

最佳答案

这里有一个小例子来向您展示这个想法。如果您的体积很大,则不建议:

import pandas as pd

df = pd.DataFrame([[1, {'abc':11}], [2, {'def':22, 'ghi':33}]], columns=['id', 'dct'])

lst = []

for index, row in df.iterrows():
    for key, value in row['dct'].items():
        lst.append([row['id'], key, value])


new = pd.DataFrame(lst, columns=['id', 'string', 'value'])

print(new)

关于python - 从 Pandas 列中提取嵌套字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58033552/

相关文章:

python - 无法在 PyCharm 中安装 PyTorch (Python 3.9/macOS)

python - Seaborn FacetGrid 条形图和色调

python - 数据框到列表格式

python - Pandas 数据框的一列中缺少数据

python - lgb.train ValueError : The truth value of an array with more than one element is ambiguous. 使用 a.any() 或 a.all()

python - 如何获取项目索引或数字以及字典中的键,值

python - 使用 Pytorch 进行深度学习 : understanding the neural network example

python - 使用单个变量索引到嵌套字典

python - 在 Twisted 中使用 DeferredQueue 进行任务间通信

python - 如何将列表值与不完全相等的数据框列进行比较?