【问题标题】:python 3.x about append function——IndexError: single positional indexer is out-of-boundspython 3.x 关于追加函数——IndexError: single positional indexer is out-of-bounds
【发布时间】:2018-03-26 05:44:04
【问题描述】:
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

【问题讨论】:

  • 看起来你的问题都是代码。您需要为您的问题提供上下文,并格式化所有代码块(选择它们,然后按
  • 谢谢!我现在试试。

标签: python-3.x pandas append


【解决方案1】:

您正在尝试附加 Averge 数据框的子集,但您没有正确索引数据框。如果您想要Avergei+1 行,请使用.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

【讨论】:

    【解决方案2】:

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

    感谢安德鲁·里斯的提示! 现在我已经解决了!

    首先,对于 i in range(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
    

    如果大家有什么不对的,欢迎!

    【讨论】:

      猜你喜欢
      • 2021-02-21
      • 1970-01-01
      • 2021-05-07
      • 2021-10-18
      • 1970-01-01
      • 2017-04-09
      • 1970-01-01
      • 2021-12-17
      • 2020-05-22
      相关资源
      最近更新 更多