【问题标题】:DataFrame with MultiIndex to dict带有 MultiIndex 的 DataFrame 到 dict
【发布时间】:2016-12-28 07:32:26
【问题描述】:

我有一个带有 MultiIndex 的数据框。我想知道我是否以正确的方式创建了数据框(见下文)。

             01.01  02.01  03.01  04.01
bar total1     40     52     18     11
    total2     36     85      5     92
baz total1     23     39     45     70
    total2     50     49     51     65
foo total1     23     97     17     97
    total2     64     56     94     45
qux total1     13     73     38      4
    total2     80      8     61     50

df.index.values 结果:

array([('bar', 'total1'), ('bar', 'total2'), ('baz', 'total1'),
       ('baz', 'total2'), ('foo', 'total1'), ('foo', 'total2'),
       ('qux', 'total1'), ('qux', 'total2')], dtype=object)

df.index.get_level_values 结果:

<bound method MultiIndex.get_level_values of MultiIndex(levels=[[u'bar', u'baz', u'foo', u'qux'], [u'total1', u'total2']],
           labels=[[0, 0, 1, 1, 2, 2, 3, 3], [0, 1, 0, 1, 0, 1, 0, 1]],names=[]

我最终希望将 df 转换为字典的字典,这样第一个字典键是 ['bar','baz','foo','qux'] 之一,值是日期和内部字典由'total1'和'totals2'作为键组成,值是df的整数。 另一种解释,例如,如果 dict1 是 dict 然后调用:

dict1['bar']

将导致输出:

{u'bar':{'01.01':{'total1':40,'total2':36},'02.01':{'total1':52,'total2':85},'03.01':{'total1':18,'total2':5},'04.01':{'total1':11,'total2':92} } }

为了实现这一目标,我需要如何以及需要改变什么?这是索引问题吗?

【问题讨论】:

  • 你试过df.to_dict()吗?
  • @albert yes 和 df.to_dict() 导致:{'01.01': {('bar', 'total1'): 40, ('bar', 'total2'): 36, ('baz', 'total1'): 23, ('baz', 'total2'): 50,etc..df.to_dict('index') 导致:('bar', 'total1'): {'01.08': 40, '02.08': 52, '03.08': 18, '04.08': 11}, ('bar', 'total2'): {'01.08': 36, '02.08': 85, '03.08': 5, '04.08': 92}。所以它让我接近了我想去的地方,这就是为什么我认为这可能是数据框形成的问题。
  • 您可以查看df.to_csv() 支持的选项/参数,因为它们可以让您操纵数据的转换方式:pandas.pydata.org/pandas-docs/stable/generated/… 我建议df.to_csv('index'),但没有尝试过.

标签: python pandas dictionary


【解决方案1】:

将整个数据帧转换为字典试试:

df.groupby(level=0).apply(lambda df: df.xs(df.name).to_dict()).to_dict()

{'bar': {'01.01': {'total1': 40, 'total2': 36},
  '02.01': {'total1': 52, 'total2': 85},
  '03.01': {'total1': 18, 'total2': 5},
  '04.01': {'total1': 11, 'total2': 92}},
 'baz': {'01.01': {'total1': 23, 'total2': 50},
  '02.01': {'total1': 39, 'total2': 49},
  '03.01': {'total1': 45, 'total2': 51},
  '04.01': {'total1': 70, 'total2': 65}},
 'foo': {'01.01': {'total1': 23, 'total2': 64},
  '02.01': {'total1': 97, 'total2': 56},
  '03.01': {'total1': 17, 'total2': 94},
  '04.01': {'total1': 97, 'total2': 45}},
 'qux': {'01.01': {'total1': 13, 'total2': 80},
  '02.01': {'total1': 73, 'total2': 8},
  '03.01': {'total1': 38, 'total2': 61},
  '04.01': {'total1': 4, 'total2': 50}}}

要转换一个特定的列,请在将其转换为字典之前选择,即

df.groupby(level=0).apply(lambda df: df.xs(df.name)[colname].to_dict()).to_dict()

【讨论】:

  • 一个很好的答案先生。
  • @jezrael 它已经是一个很好的答案。感觉就像为未来的读者完成它。
  • 我删除了那里的链接。
  • 我一整天都在寻找这种方法。太好了,谢谢!
  • 我被这个答案打开了。
猜你喜欢
  • 1970-01-01
  • 2016-02-04
  • 1970-01-01
  • 2018-11-28
  • 1970-01-01
  • 2019-03-22
  • 2016-12-18
  • 2018-08-11
  • 2021-10-06
相关资源
最近更新 更多