converting dictionary to binary in python

耗尽温柔 提交于 2019-12-14 03:55:39

问题


I have a dictionary with keys as my customer ID and values as my movie id. Though the customer has watched the same movie many times, I want it to make as one. Here I need to convert my dictionary to binary data. In all the rows I need the customers ID's and columns as movie id's, where if the customer has watched the movie, it gives 1 else 0.

d = {'121212121' : 111, 222, 333, 333,444, 444, '212121212' : 222, 555, 555, 666, '212123322' : 555, 666, 666, 666, 777}

Desired output :

customer ID 111 222 333 444 555 666 777
121212121   1   1   1   1   0   0   0
212121212   0   1   0   0   1   1   0
121323231   0   0   0   0   1   1   1

I have tried using count vectorizer()

code :

cv = CountVectorizer()
movies = cv.fit_transform(cust['movies_list'])
cols = cv.vocabulary_
movies_ = pd.DataFrame(movies.toarray(), columns = cols, index = 
cust['customer_id'])
movies_

output :

customer ID 111 222 333 444 555 666 777
212121212   1   1   2   2   0   0   0
121212121   0   1   0   0   2   1   0
121323231   0   0   0   0   1   3   1

The customer Id's dint match and I got a count on how many times he watched the movie.


回答1:


It looks like you can just use clip_upper to clip positive values to 1.

movies_.clip_upper(1)

           111  222  333  444  555  666  777
121212121    1    1    1    1    0    0    0
212121212    0    1    0    0    1    1    0
212123322    0    0    0    0    1    1    1

Here's an alternative solution starting with d. You can use pd.get_dummies, followed by clip_upper.

import pandas as pd
df = pd.concat([
          pd.Series(v, name=k).astype(str) for k, v in d.items()  # `d` is your dict
     ], 
     axis=1
)
pd.get_dummies(df.stack()).sum(level=1).clip_upper(1)

           111  222  333  444  555  666  777
121212121    1    1    1    1    0    0    0
212121212    0    1    0    0    1    1    0
212123322    0    0    0    0    1    1    1


来源:https://stackoverflow.com/questions/48657151/converting-dictionary-to-binary-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!