如何在Python3中将数据帧转换为dict

时间:2017-01-02 15:51:28

标签: 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

我想把它变成像

这样的词典
{userId:{movieId:rating}}

e.g

{
 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]

有人可以帮帮我吗?

1 个答案:

答案 0 :(得分:4)

您可以groupby使用iterrows

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}
}

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

<select class="form-control" id="id_type" name="type" onchange="filterUser(this.value)">
    <option value="">Choose payment</option>
    <?php
    for($i=0;$i<count($types);$i++){
        if($t==$types[$i]['title_type']){
            echo '<option selected  value="'.$types[$i]['id'].'" >' . $types[$i]['title_type'] . '</option>';
        }
        else {
            echo '<option value="'.$types[$i]['id'].'" >' . $types[$i]['title_type'] . '</option>';
        }
    }
    ?>
</select>
<br>

<br><input type="radio" name="del" id="del" value="del" onchange="filterUser(this.value)">Delete<br>