代码之家  ›  专栏  ›  技术社区  ›  Sociopath

将PADAS数据帧转换为字典,其中键是索引,值是列值列表

  •  3
  • Sociopath  · 技术社区  · 6 年前

    我有一个数据框架

    DF:

        cola    colb   colc   cold
    0      0    'a'     'b'   'c'
    1      1    'd'     None  None
    2      2    'g'     'h'   None
    

    我想把它转换成 dict 其中,索引是键,列值列表是如下所示的值:

    d = {0 : [0,'a','b','c'], 1: [1,'d'], 2: [2,'g','h'] }
    

    我试过什么 :

    df.to_dict(orient='index')
    

    我也尝试了其他的价值观 orient 参数,但不起作用。

    编辑 :

    我想忽略字典中的空值,如输出中所示。

    1 回复  |  直到 6 年前
        1
  •  5
  •   jezrael    6 年前

    使用 DataFrame.to_dict 具有 orient='list' ,仅在转置之前 DataFrame :

    d = df.T.to_dict(orient='list')
    print (d)
    {0: [0, 'a', 'b', 'c'], 1: [1, 'd', 'e', 'f'], 2: [2, 'g', 'h', 'i']}
    

    编辑:

    d = df.stack().groupby(level=0).apply(list).to_dict()
    print (d)
    {0: [0, 'a', 'b', 'c'], 1: [1, 'd'], 2: [2, 'g', 'h']}
    

    或:

    d = {k:[x for x in v if x is not None] for k, v in df.T.to_dict(orient='list').items()}
    print (d)
    {0: [0, 'a', 'b', 'c'], 1: [1, 'd'], 2: [2, 'g', 'h']}