将长格式的 pandas 数据框转换为字典

1 投票
3 回答
1344 浏览
提问于 2025-04-30 23:24

我在寻找如何把一个pandas的DataFrame转换成字典的帮助和文档,想要的结果是列作为键,行作为值。不过,当我想把某一列的值作为键,而另一列的相关值作为值时,我就卡住了。比如说,像下面这样的DataFrame:

a b
1 car
1 train
2 boot
2 computer
2 lipstick

我希望能转换成这样的字典:{'1': ['car','train'], '2': ['boot','computer','lipstick']}

我觉得这应该是个简单的事情,但我想不出办法。我试过用df.groupby('a').to_dict(),但没有成功。

有没有什么建议呢?

暂无标签

3 个回答

1

是的,因为 DataFrameGroupBy 这个东西没有 to_dict 这个功能,只有 DataFrame 才有 to_dict 这个功能。

DataFrame.to_dict(outtype='dict') 可以把 DataFrame 转换成字典。

你可以在 这里 了解更多关于 DataFrame.to_dict 的信息。

看看这个:

import pandas as pd

df = pd.DataFrame([np.random.sample(9), np.random.sample(9)])
df.columns = [c for c in 'abcdefghi']
# it will convert the DataFrame to dict, with {column -> {index -> value}}
df.to_dict()
{'a': {0: 0.53252618404947039, 1: 0.78237275521385163},
 'b': {0: 0.43681232450879315, 1: 0.31356312459390356},
 'c': {0: 0.84648298651737541, 1: 0.81417040486070058},
 'd': {0: 0.48419015448536995, 1: 0.37578177386187273},
 'e': {0: 0.39840348154035421, 1: 0.35367537180764919},
 'f': {0: 0.050381560155985827, 1: 0.57080653289506755},
 'g': {0: 0.96491634442628171, 1: 0.32844653606404517},
 'h': {0: 0.68201236712813085, 1: 0.0097104037581828839},
 'i': {0: 0.66836630467152902, 1: 0.69104505886376366}}

type(df)
pandas.core.frame.DataFrame

# DataFrame.groupby is another type
type(df.groupby('a'))
pandas.core.groupby.DataFrameGroupBy

df.groupby('a').to_dict()
AttributeError: Cannot access callable attribute 'to_dict' of 'DataFrameGroupBy' objects, try using the 'apply' method
2

你可以把这看作是一个分组聚合的操作,也就是说,它会把每一组的数据变成一个值——在这个例子中,就是一个列表:

In [85]: df.groupby(['a'])['b'].agg(lambda grp: list(grp))
Out[85]: 
a
1                  [car, train]
2    [boot, computer, lipstick]
dtype: object

In [68]: df.groupby(['a'])['b'].agg(lambda grp: list(grp)).to_dict()
Out[68]: {1: ['car', 'train'], 2: ['boot', 'computer', 'lipstick']}
1

你不能直接对分组后的结果使用 to_dict(),但是你可以用它来自己构建字典。下面的代码可以和你提供的例子一起使用。

import pandas as pd

df = pd.DataFrame(dict(a=[1,1,2,2,2],
                       b=['car', 'train', 'boot', 'computer', 'lipstick']))
# Using a loop
dt = {}
for g, d in df.groupby('a'):
    dt[g] = d['b'].values

# Using dictionary comprehension
dt2 = {g: d['b'].values for g, d in df.groupby('a')}

现在 dtdt2 都会变成像这样的字典:

{1: array(['car', 'train'], dtype=object),
 2: array(['boot', 'computer', 'lipstick'], dtype=object)}

当然,如果你想的话,也可以把numpy数组再放回列表里。

撰写回答