简体   繁体   中英

Python Pandas to_dict function

I'm trying to create a dictionary, but can't get it to work the way I intend. I feel like I'm so close. I a df of yelp data:

import pandas as pd
file_rev = 'blah.csv'

reviews=pd.read_csv(file_rev, sep=',',header=0, nrows=10000)

cols = ['user_id', 'business_id', 'stars']
cat_rev = reviews[cols]

print cat_rev

df:

                   user_id             business_id  stars
0   Xqd0DzHaiyRqVH3WRG7hzg  vcNAWiLM4dR7D2nwwJ7nCA      5
1   H1kH6QZV7Le4zqTRNxoZow  vcNAWiLM4dR7D2nwwJ7nCA      2
2   zvJCcrpm2yOZrxKffwGQLA  vcNAWiLM4dR7D2nwwJ7nCA      4
3   KBLW4wJA_fwoWmMhiHRVOA  vcNAWiLM4dR7D2nwwJ7nCA      4
4   zvJCcrpm2yOZrxKffwGQLA  vcNAWiLM4dR7D2nwwJ7nCA      4
5   Qrs3EICADUKNFoUq2iHStA  vcNAWiLM4dR7D2nwwJ7nCA      1
6   jE5xVugujSaskAoh2DRx3Q  vcNAWiLM4dR7D2nwwJ7nCA      5
7   QnhQ8G51XbUpVEyWY2Km-A  vcNAWiLM4dR7D2nwwJ7nCA      5
8   tAB7GJpUuaKF4W-3P0d95A  vcNAWiLM4dR7D2nwwJ7nCA      1
9   GP-h9colXgkT79BW7aDJeg  vcNAWiLM4dR7D2nwwJ7nCA      5
10  uK8tzraOp4M5u3uYrqIBXg  UsFtqoBl7naz8AVUBZMjQQ      5

I want to be able to create this as a dictionary that looks like:

abc = {user1 : {business1:star_rating, business2:star_rating…, 
                businessN:star_rating}, 
       user2: {} … }

Then to access I would just: abc[user1] would give me all the places and stars that user1 reviewed.
abc[user1][place1] would give just corresponding star rating.

I've tried the to_dict panda function. I tried to groupby first, then dict(list(groupby())) , and nothing seems to convert it to how I want.

Also nope, but almost:

ddd = cat_rev.set_index('user_id').to_dict(outtype='list')

You could use groupby and a dict-comprehension:

{user_id: pd.Series(grp['stars'].values, index=grp['business_id']).to_dict() 
 for user_id, grp in df.groupby(['user_id'])}

yields

{'GP-h9colXgkT79BW7aDJeg': {'vcNAWiLM4dR7D2nwwJ7nCA': 5},
 'H1kH6QZV7Le4zqTRNxoZow': {'vcNAWiLM4dR7D2nwwJ7nCA': 2},
 'KBLW4wJA_fwoWmMhiHRVOA': {'vcNAWiLM4dR7D2nwwJ7nCA': 4},
 'QnhQ8G51XbUpVEyWY2Km-A': {'vcNAWiLM4dR7D2nwwJ7nCA': 5},
 'Qrs3EICADUKNFoUq2iHStA': {'vcNAWiLM4dR7D2nwwJ7nCA': 1},
 'Xqd0DzHaiyRqVH3WRG7hzg': {'vcNAWiLM4dR7D2nwwJ7nCA': 5},
 'jE5xVugujSaskAoh2DRx3Q': {'vcNAWiLM4dR7D2nwwJ7nCA': 5},
 'tAB7GJpUuaKF4W-3P0d95A': {'vcNAWiLM4dR7D2nwwJ7nCA': 1},
 'uK8tzraOp4M5u3uYrqIBXg': {'UsFtqoBl7naz8AVUBZMjQQ': 5},
 'zvJCcrpm2yOZrxKffwGQLA': {'vcNAWiLM4dR7D2nwwJ7nCA': 4}}

您也可以使用索引来压缩值...

d = {k:v for k,v in  zip(df.index,df.to_dict('records'))}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM