我已经在Internet上搜索了很长时间,但无济于事。
import pandas as pd
import numpy as np
import math
unames = ['user_id', 'gender', 'age', 'occupation', 'zip']
users = pd.read_table('ml-1m/users.dat', sep='::',
header=None,names=unames,engine='python')
rnames = ['user_id', 'movie_id', 'rating', 'timestamp']
ratings = pd.read_table('ml-1m/ratings.dat', sep='::',
header=None,names=rnames,engine='python')
mnames = ['movie_id', 'title', 'genres']
movies = pd.read_table('ml-1m/movies.dat', sep='::',
header=None,names=mnames,engine='python')
data=pd.merge(pd.merge(ratings,users),movies)
然后我得到一个这样的表: a DataFrame of the data
然后,我像这样处理数据
data1=pd.pivot_table(data[(data.user_id==1)],index=['title'],columns='user_id',values='rating')
然后我尝试将data1
转换为字典
Dict=data1.to_dict()
字典是这样的:
{1: {'Airplane! (1980)': 4,
'Aladdin (1992)': 4,
'Antz (1998)': 4,
'Apollo 13 (1995)': 5,
'Awakenings (1990)': 5,
'Back to the Future (1985)': 5,
'Bambi (1942)': 4,
'Beauty and the Beast (1991)': 5,
'Ben-Hur (1959)': 5,
'Big (1988)': 4,
"Bug's Life, A (1998)": 5,
'Christmas Story, A (1983)': 5,
'Cinderella (1950)': 5,
'Close Shave, A (1995)': 3,
'Dead Poets Society (1989)': 4,
'Driving Miss Daisy (1989)': 4,
'Dumbo (1941)': 5,}}
但是,我想将data1
转换成这样的字典:
{'Airplane! (1980)': 4,
'Aladdin (1992)': 4,
'Antz (1998)': 4,
'Apollo 13 (1995)': 5,
'Awakenings (1990)': 5,
'Back to the Future (1985)': 5,
'Bambi (1942)': 4,
'Beauty and the Beast (1991)': 5,
'Ben-Hur (1959)': 5,
'Big (1988)': 4,
"Bug's Life, A (1998)": 5,
'Christmas Story, A (1983)': 5,
'Cinderella (1950)': 5,
'Close Shave, A (1995)': 3,
'Dead Poets Society (1989)': 4,
'Driving Miss Daisy (1989)': 4,
'Dumbo (1941)': 5,}
区别在于第一个版本具有一个1
作为密钥,那么我该如何像第二个那样进行转换?
答案 0 :(得分:0)
按1
的列Series
的名称进行选择,并转换为dict
,也最好更改变量名称Dict
,如注释中提到的@jpp:
d = data1[1].to_dict()