首页 > 解决方案 > 数据框中的冗余值用作键,另一列用作值

问题描述

我有一个像

name  count  title
a       1      c1
a       2      c2
a       3      b1
b       4      f1
b       5      f2
c       6      g1

我想将它转移到一个name作为键和title作为值的字典。

我希望输出像

{a: [c1, c2, b1], b: [f1, f2], c: [g1]}

我试过这个:

sites = {} 
features = []       
for index,row in df.iterrows():
    sites[row["name"]] = features.append(row["title"])

并得到了一个字典,其None值为

{a: None, b: None, c: None}

为什么我会得到None,我怎样才能正确地做到这一点?


我也试过这个:

your_dict = df.groupby(["Name"])["title"].apply(list).to_dict().get("Name")

也获得了None价值。

标签: python

解决方案


your_dict = df.groupby(["name"])["title"].apply(list).to_dict()

推荐阅读