2017-10-14 46 views
0
import numpy as np 
import pandas 

data=pandas.read_table('u.data',names=['user id','item id','rating','timestamp'] 

user=pandas.read_table('u.user', sep='|',names=['user id ','age','gender','occupation','zip code']) 

item=pandas.read_table(r'u.item', sep='|',names=['movie id','movie title','release date','video release date', 
'IMDb URL','unknown','Action','Adventure','Animation',"Children's", 
'Comedy','Crime','Documentary','Drama','Fantasy','Film-Noir', 
'Horror','Musical','Mystery','Romance','Sci-Fi','Thriller',' War',' Western']) 

data.sort_values('user id', inplace=True) 

Averge=pandas.pivot_table(data, values='rating', columns=['user id'], aggfunc='mean') 

M=[] 
F=[] 

#There is an error 

for i in range(944): 
    if user.iloc[i]['gender']=='M': 
     M.append(Averge[i+1]) 
    else: 
     F.append(Averge[i+1]) 

IndexError: single positional indexer is out-of-bounds 
+0

它看起来像你的问题是所有的代码。您需要为您的问题提供上下文,并格式化所有代码块(选择它们,然后按) –

+0

谢谢!我现在尝试。 –

回答

0

你试图追加Averge数据帧的一个子集,但你没有正确索引数据帧。如果您想要i+1行的Averge,请使用.iloc

例如:

import pandas as pd 

df = pd.DataFrame({'foo':[1,2,3], 'bar':[9,8,7]}) 
for i in range(2): 
    print(df.iloc[i+1]) 

# output 
bar 8 
foo 2 
Name: 1, dtype: int64 
bar 7 
foo 3 
Name: 2, dtype: int64 
0

我很抱歉,我的英语很差。 我希望你会知道我想表达什么。

谢谢andrew_reece的提示! 现在我已经解决了!

首先,对于我在范围(943):944以外的界限,您最好知道这些数据。第二,因为我的数据很特殊,Averge.iloc [0] [i + 1]是正确的。只有一行。 就像它!

Averge=pandas.pivot_table(data, values='rating', columns=['user id'], aggfunc='mean') 

M=[] 
F=[] 

for i in range(943): 
    #944 will make it-> IndexError: single positional indexer is out-of-bounds 
    if (user.iloc[i]['gender']=='M'): 
     M.append(Averge.iloc[0][i+1]) 
    else: 
     F.append(Averge.iloc[0][i+1]) #df.iloc[0][1] the first data 

如果每个人都有问题,欢迎您!