python - 如何在 Python3 中将数据框转换为字典

标签 python pandas dictionary nested

我在网上找了好久都没找到。请帮助或尝试提供一些想法如何实现这一目标

我使用 pandas 读取 MovieLens csv 文件

ratings = pd.read_table('ml-latest-small/ratings.csv')

然后我得到一个这样的表:

userId  movieId rating  timestamp
1       31      2.5     1260759144
1       1029    3.0     1260759179
1       1061    3.0     1260759182
1       1129    2.0     1260759185
1       1172    4.0     1260759205
2       31      3.0     1260759134
2       1111    4.5     1260759256

我想把它改成像dict一样

{userId:{movieId:rating}}

例如

{
 1:{31:2.5,1029:3.0,1061,3.0,1129:2.0,1172:4.0},
 2:{31:3.0,1111:4.5}
}

我试过这段代码,但失败了:

for user in ratings['userId']:
for movieid in ratings['movieId']:
    di_rating.setdefault(user,{})
    di_rating[user][movieid]=ratings['rating'][ratings['userId'] == user][ratings['movieId'] == movieid]

有人可以帮帮我吗?

最佳答案

您可以使用 groupbyiterrows :

d = df.groupby('userId').apply(lambda y: {int(x.movieId): x.rating for i, x in y.iterrows()})
      .to_dict()
print (d)
{
1: {1129: 2.0, 1061: 3.0, 1172: 4.0, 1029: 3.0, 31: 2.5}, 
2: {1111: 4.5, 31: 3.0}
}

删除答案的另一种解决方案:

d1 = df.groupby('userId').apply(lambda x: dict(zip(x['movieId'], x['rating']))).to_dict()
print (d1)
{
1: {1129: 2.0, 1061: 3.0, 1172: 4.0, 1029: 3.0, 31: 2.5}, 
2: {1111: 4.5, 31: 3.0}
}

关于python - 如何在 Python3 中将数据框转换为字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41429746/

相关文章:

python - 如何解释奇异值分解结果(Python 3)?

python - Pandas:需要一种更快的索引切片方法

python - 数据帧 : Add 'inplace' a column with the cumcount() of the dates appeared in the datetime. 索引

c# - 种子随机分析 :The given key was not present in the dictionary

java - 在这种情况下,TreeBasedTable.create().rowMap().get(rowKey) 将返回一个空映射

python - 如何使用 reportlab 在 PDF 中添加总页数

python - 如何在没有 root 访问权限的情况下在启动时运行 bash 脚本?

python - 信号未从线程传递到 GUI

python - 通过最后 N 个值过滤 Pandas 数据帧

c# - 如何将键交换为值和将值交换为字典中的键