python - Pandas MultiIndex(超过 2 个级别)DataFrame 到嵌套 Dict/JSON

标签 python pandas dictionary multi-index

这个问题类似于this one ,但我想更进一步。是否可以扩展解决方案以处理更多级别?多级数据帧的 .to_dict() 方法有一些有前途的选项,但它们中的大多数将返回由元组索引的条目(即 (A, 0, 0): 274.0 ) 而不是将它们嵌套在字典中。

举个我希望完成的例子,考虑这个多索引数据框:

data = {0: {
        ('A', 0, 0): 274.0, 
        ('A', 0, 1): 19.0, 
        ('A', 1, 0): 67.0, 
        ('A', 1, 1): 12.0, 
        ('B', 0, 0): 83.0, 
        ('B', 0, 1): 45.0
    },
    1: {
        ('A', 0, 0): 254.0, 
        ('A', 0, 1): 11.0, 
        ('A', 1, 0): 58.0, 
        ('A', 1, 1): 11.0, 
        ('B', 0, 0): 76.0, 
        ('B', 0, 1): 56.0
    }   
}
df = pd.DataFrame(data).T
df.index = ['entry1', 'entry2']
df
# output:

         A                              B
         0              1               0
         0      1       0       1       0       1
entry1   274.0  19.0    67.0    12.0    83.0    45.0
entry2   254.0  11.0    58.0    11.0    76.0    56.0

你可以想象我们这里有很多条记录,而不仅仅是两条,而且索引名称可以是更长的字符串。您如何将其转换为如下所示的嵌套字典(或直接转换为 JSON):

[
 {'entry1': {'A': {0: {0: 274.0, 1: 19.0}, 1: {0: 67.0, 1: 12.0}},
  'B': {0: {0: 83.0, 1: 45.0}}},
 'entry2': {'A': {0: {0: 254.0, 1: 11.0}, 1: {0: 58.0, 1: 11.0}},
  'B': {0: {0: 76.0, 1: 56.0}}}}
]

我认为一定程度的递归可能会有所帮助,可能类似于 this , 但到目前为止还没有成功。

最佳答案

所以,你真的需要在这里做两件事:

  • df.to_dict()
  • 将其转换为嵌套字典。

df.to_dict(orient='index') 给你一个以索引为键的字典;它看起来像这样:

>>> df.to_dict(orient='index')
{'entry1': {('A', 0, 0): 274.0,
  ('A', 0, 1): 19.0,
  ('A', 1, 0): 67.0,
  ('A', 1, 1): 12.0,
  ('B', 0, 0): 83.0,
  ('B', 0, 1): 45.0},
 'entry2': {('A', 0, 0): 254.0,
  ('A', 0, 1): 11.0,
  ('A', 1, 0): 58.0,
  ('A', 1, 1): 11.0,
  ('B', 0, 0): 76.0,
  ('B', 0, 1): 56.0}}

现在你需要嵌套它。这是一个技巧 from Martijn Pieters这样做:

def nest(d: dict) -> dict:
    result = {}
    for key, value in d.items():
        target = result
        for k in key[:-1]:  # traverse all keys but the last
            target = target.setdefault(k, {})
        target[key[-1]] = value
    return result

把这些放在一起:

def df_to_nested_dict(df: pd.DataFrame) -> dict:
    d = df.to_dict(orient='index')
    return {k: nest(v) for k, v in d.items()}

输出:

>>> df_to_nested_dict(df)
{'entry1': {'A': {0: {0: 274.0, 1: 19.0}, 1: {0: 67.0, 1: 12.0}},
  'B': {0: {0: 83.0, 1: 45.0}}},
 'entry2': {'A': {0: {0: 254.0, 1: 11.0}, 1: {0: 58.0, 1: 11.0}},
  'B': {0: {0: 76.0, 1: 56.0}}}}

关于python - Pandas MultiIndex(超过 2 个级别)DataFrame 到嵌套 Dict/JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50929768/

相关文章:

python - Pandas :分组

python - 数据框中列表的 Pandas 平均值

python - 使用 Matplotlib.dates.datestr2num 将 pandas DatetimeIndex 转换为 'float days format'

python - 如何根据某种等价关系从矩阵列表中删除重复项?

python - Pandas:每月制作 DataFrame 切片

python - 将字典中的下一项与上一项进行比较

python - 算法设计——何时使用字典与列表来跟踪值

python - 如何将列表字典写入字符串而不是 CSV 文件?

python - 尝试使用 Scrapy 抓取表格

python - 带有 python 扩展的 VS2015 链接器错误