首页 > 解决方案 > 列表的数据框到 multiIndex 数据框

问题描述

我有一个列表数据框,列表中的每个值代表更大数据集的平均值、标准差和值的数量。我想为该列表中的三个值创建一个子索引。

一个示例数据框是:

np.random.seed(2)
d={i: {j:[np.random.randint(10) for i in range(0,3)] for j in ['x','y','z']} for i in ['a','b','c']}
pd.DataFrame.from_dict(d,orient='index')

这使:

    x   y   z
a   [1, 4, 5]   [7, 4, 4]   [0, 6, 3]
b   [7, 1, 9]   [1, 3, 8]   [3, 6, 2]
c   [1, 6, 6]   [6, 5, 0]   [6, 5, 9]

我想:

    x              y              z
    mean std count mean std count mean std count
a   1    4   5     7    4   4     0    6   3
b   7    1   9     1    3   8     3    6   2
c   1    6   6     6    5   0     6    5   9

标签: pandasmulti-index

解决方案


您可以使用numpy concatenatenumpy vstack连接内部列表,构建 MultiIndex 列,然后生成一个新数据框:

np.random.seed(2)
d = {
    i: {j: [np.random.randint(10) for i in range(0, 3)] for j in ["x", "y", "z"]}
    for i in ["a", "b", "c"]
}
df = pd.DataFrame.from_dict(d, orient="index")
df

        x          y            z
a   [8, 8, 6]   [2, 8, 7]   [2, 1, 5]
b   [4, 4, 5]   [7, 3, 6]   [4, 3, 7]
c   [6, 1, 3]   [5, 8, 4]   [6, 3, 9]

data = np.vstack([np.concatenate(entry) for entry in df.to_numpy()])
columns = pd.MultiIndex.from_product([df.columns, ["mean", "std", "count"]])
pd.DataFrame(data, columns=columns, index = df.index)


                   x                 y                    z
    mean    std count   mean    std count   mean    std count
a      8    8   6        2      8   7       2       1   5
b      4    4   5        7      3   6       4       3   7
c      6    1   3        5      8   4       6       3   9

更新:2021 年 10 月 5 日

另一种选择是将初始数据帧转换为字典并与 pd.concat 连接:

outcome = {k:pd.DataFrame([*v], 
                          columns = ['mean', 'std', 'count'], 
                          index = v.index) 
           for k,v in df.items()}

pd.concat(outcome, axis = 1)
 
     x              y              z          
  mean std count mean std count mean std count
a    8   8     6    2   8     7    2   1     5
b    4   4     5    7   3     6    4   3     7
c    6   1     3    5   8     4    6   3     9


推荐阅读