【问题标题】:Pandas: how to convert dataframe with duplicate index values to a dictionaryPandas:如何将具有重复索引值的数据框转换为字典
【发布时间】:2021-02-14 19:12:43
【问题描述】:

我有一个 DataFrame df_test 如下:

a   b   c
5   7   1
6   7   0
15  17  1
16  17  0

问题

我正在尝试从此数据框中创建一个字典,其中 b 列作为索引。请注意b 列中的值是重复的。当我使用下面给出的代码创建字典时,它只显示最后一行作为输出。如何创建字典以包含数据框中提供的所有信息。

测试代码

以下是代码:

df_test.set_index('b', inplace=True)
df_test.T.to_dict(orient="list")

输出

{7: [6, 0], 17: [16, 0]}

期望的输出

输出应包括与每个键对应的所有行,而不仅仅是最后一行。类似于但不限于如下所示的输出:

{7: [[5, 1],[6, 0]], 17: [[15, 1],[16, 0]]}

【问题讨论】:

    标签: python pandas dataframe dictionary indexing


    【解决方案1】:

    使用DataFrame.set_index 处理所有在lambda 函数中没有b 的列,以便转换为嵌套列表,然后转换为字典:

    d = df_test.set_index('b').groupby('b').apply(lambda x : x.to_numpy().tolist()).to_dict()
    print (d)
    {7: [[5, 1], [6, 0]], 17: [[15, 1], [16, 0]]}
    

    【讨论】:

      猜你喜欢
      • 2022-01-07
      • 1970-01-01
      • 2018-06-03
      • 2013-12-05
      • 2020-04-11
      • 1970-01-01
      • 1970-01-01
      • 2021-01-02
      • 1970-01-01
      相关资源
      最近更新 更多