如何从具有由数组组成的值的字典中创建 Pandas DataFrame?

How to make a Pandas DataFrame from a dictionary that has values that consists of arrays?

目前我有一个字典,每个键都有一个数组(有很多列表)。我想把这本字典变成一个 DataFrame。这是字典目前的样子:

然而,我想要的格式是这样的:

title                                  A       C      mC      G      T
000805ef-05c0-40d8-be27-a88ad2932a68  255     255     0      255    255
000805ef-05c0-40d8-be27-a88ad2932a68  255     20      235    255    255
......
00723b5f-95a1-44c4-93b5-ba4adb8ea5b7  255     255     0      255    255

我只是简单地尝试使用 pd.DataFrame(dict) 但那没有用。我也试过 pd.DataFrame.from_dict(dict) 也没有用。我想我需要更多地操作字典,以便在转换之前了解它在数据框中的外观。任何帮助将不胜感激!

您可以 vstack 值和 repeat 键:

# dictionary with numpy arrays as values
d = {
    'a': np.ones((2, 3), dtype=np.int),
    'b': np.eye(3, dtype=np.int),
}

df = pd.DataFrame(
    np.vstack(list(d.values())),
    index = np.repeat(
        list(d.keys()),
        [len(x) for x in d.values()]
    ),
    columns = ['x', 'y', 'z']
)

df

输出:

   x  y  z
a  1  1  1
a  1  1  1
b  1  0  0
b  0  1  0
b  0  0  1