【问题标题】:How to transform dataframe to dict in Python3如何在 Python3 中将数据框转换为 dict
【发布时间】:2017-05-16 17:35:12
【问题描述】:

我在网上搜索了很长时间,但无济于事。请帮助或尝试提供一些想法如何实现这一目标

我使用 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]

有人可以帮帮我吗?

【问题讨论】:

    标签: python pandas dictionary nested


    【解决方案1】:

    您可以将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}
    }
    

    【讨论】:

    • 非常感谢!但似乎“movieId”转换为浮点类型
    • 你可以投到int - d = df.groupby('userId').apply(lambda y: { int(x.movieId): x.rating for i, x in y.iterrows()}).to_dict()
    猜你喜欢
    • 2020-06-16
    • 2019-09-27
    • 2021-10-15
    • 2023-03-22
    • 2013-09-21
    • 2020-08-07
    • 2021-05-14
    • 2021-10-08
    相关资源
    最近更新 更多