pandas 如何从python dicts创建带有多个索引的 Dataframe

lfapxunr  于 2023-04-28  发布在  Python
关注(0)|答案(1)|浏览(131)

我从一些数据中读取信息,并根据这些信息创建一个dict。这些内容如下所示:

('B60_L50', '128', 'CP', 'S5', 'side', '2022-05-05_20-04-42 S101_z200'): defaultdict(<class 'dict'>, {200: 6.352113278610182}), 
('B60_L50', '128', 'CP', 'S5', 'side', '2022-05-05_20-04-42 S102_z200'): defaultdict(<class 'dict'>, {200: 5.621293764849755}), 
('B60_L50', '128', 'CP', 'S5', 'side', '2022-05-05_20-04-42 S103_z200'): defaultdict(<class 'dict'>, {200: 5.979359334924249}), 
('B60_L50', '128', 'CP', 'S5', 'side', '2022-05-05_20-04-42 S104_z200'): defaultdict(<class 'dict'>, {200: 3.587064282376453})})

其中('B60_L50', '128', 'CP', 'S5', 'side', '2022-05-05_20-04-42 S104_z200')是多重索引的值。{200: 6.352113278610182}表示列名(200)和单元格的值。之前我创建了一个dataframe并逐个插入值,但是由于元素的数量太多,它需要太长时间。因此我认为从数据创建一个dict更有意义。
这就是我如何构建dataframe:

ind = pd.MultiIndex.from_product(
        [coils, frequencies, polarisations, s_values, orientations, titles],
        names=["Coil", "Frequency", "Polarisation", "S-Value", "Orientation", "First_Row_Element"])
    df = pd.DataFrame(None, index=ind, columns=list(landmarks))  # Convert landmarks set to list
wnavrhmk

wnavrhmk1#

假设您的数据可以表示为字典,您可以使用pd.MultiIndex.from_tuples创建MultiIndex

d = {('B60_L50', '128', 'CP', 'S5', 'side', '2022-05-05_20-04-42 S101_z200'): {200: 6.352113278610182},
     ('B60_L50', '128', 'CP', 'S5', 'side', '2022-05-05_20-04-42 S102_z200'): {200: 5.621293764849755},
     ('B60_L50', '128', 'CP', 'S5', 'side', '2022-05-05_20-04-42 S103_z200'): {200: 5.979359334924249},
     ('B60_L50', '128', 'CP', 'S5', 'side', '2022-05-05_20-04-42 S104_z200'): {200: 3.587064282376453}}

index = pd.MultiIndex.from_tuples(d, names=["Coil", "Frequency", "Polarisation", "S-Value", "Orientation", "First_Row_Element"])
df = pd.DataFrame(d.values(), index=index)
print(df)

                                                                                       200
Coil    Frequency Polarisation S-Value Orientation First_Row_Element
B60_L50 128       CP           S5      side        2022-05-05_20-04-42 S101_z200  6.352113
                                                   2022-05-05_20-04-42 S102_z200  5.621294
                                                   2022-05-05_20-04-42 S103_z200  5.979359
                                                   2022-05-05_20-04-42 S104_z200  3.587064

相关问题