PYTHON Pandas Dataframe SENSEI DataFrame Strange IndexError in the iloc[] code for copying rows from one dataframe to another

PYTHON Pandas Dataframe SENSEI DataFrame Strange IndexError in the iloc[] code for copying rows from one dataframe to another

在 Windows 10 和 2 个 GPU 机器上基于 Anaconda3 在 Spyder 上使用 Python 3.5:

我正在使用 Sensei 日本空手道大师数据集来检查过去 5 年中哪些大师获得了硕士学位,并将他们的所有行复制到另一个 Pandas Dataframe sensei5yrs 以进行进一步处理:

我需要逐行从一个 Pandas 数据帧 "sensei" 复制到另一个 Pandas 数据帧 sensei5yrs 我正在使用下面的代码,但它失败了:

for i in range(0, len(sensei)-1):
    #print(sensei.iloc[i]['Year'], sensei.iloc[i]['Date']
    chk=sensei.iloc[i]['Year']
    print("Checker: ",chk, sensei)
    if str(chk) in ['2017','2016','2015','2014','2013']:
        print("Found one year")
        sensei5yrs.iloc[i]=sensei.iloc[i]

错误出现在上面代码的最后一行:

IndexError: single positional indexer is out-of-bounds

print(sensei5yrs)
Empty DataFrame
Columns: [Date, OpenScore, HighScore, LowScore, CloseScore, Adj CloseScore, 
VolumeFights, Year]

sensei pandas 数据框具有以下结构和数据:

print(sensei)
Columns: [Date, OpenScore, HighScore, LowScore, CloseScore, Adj CloseScore,VolumeFights, Year]
0 2000-11-23  3837.110107  3871.340088  3826.419922  3852.399902  3852.399902   12800  2000
1 2017-11-24  3860.520020  3889.560059  3856.580078  3868.340088  3868.340088    12800  2017   

例如'Year'列中For循环遇到2017时的错误如下:

IndexError: single positional indexer is out-of-bounds

PS:上面的代码运行正常,直到遇到一行 Year==['2017','2016','2015','2014','2013'] 立即遇到'Year' 列中的上述任何年份都会抛出上述 IndexError

非常感谢所有试图解决这个难题的人。

您没有必要通过遍历每一行来执行此操作。您可以通过在原始数据帧上使用布尔索引来创建一个新的 sensei5 对象,如下所示:

import pandas as pd
year = ['2017','2010','2015','2014','2013', '2013','2011','2012','2014','2010']
master = ['foo', 'bar', 'foo1', 'bar1', 'foo2', 'bar2', 'foo3', 'bar3', 'foo4', 'bar4']

sensei = pd.DataFrame({'year' : year, 'master' : master})
sensei5 = sensei[2017 - sensei['year'].astype(int) <=5]

给出:

  master  year
0    foo  2017
2   foo1  2015
3   bar1  2014
4   foo2  2013
5   bar2  2013
7   bar3  2012
8   foo4  2014

但是,如果您必须使用 loc 通过迭代来完成,那么以下似乎可以正常工作。您可能会遇到问题,因为您要从数据帧的长度中减去 1。我怀疑你不打算这样做,因为 python 范围在停止条件之前停止一个:

newSensei5 = pd.DataFrame(columns = sensei.columns)
for row in range(len(sensei)):
    if int(sensei.loc[row, 'year']) >=2012:
        newSensei5.loc[row, :] = sensei.loc[row, :]

给出:

In [23]: newSensei5
Out[23]:
  master  year
0    foo  2017
2   foo1  2015
3   bar1  2014
4   foo2  2013
5   bar2  2013
7   bar3  2012
8   foo4  2014

EDIT 我没注意到你也传递了数据。我按如下方式重新创建了它:

Columns = ["Date", "OpenScore", "HighScore", "LowScore", "CloseScore", "Adj CloseScore", "VolumeFights", "Year"]
a = [2000-11-23, 3837.110107,  3871.340088, 3826.419922,  3852.399902,  3852.399902 ,  12800 , "2000"]
b = [2017-11-24, 3860.520020,  3889.560059, 3856.580078,  3868.340088,  3868.340088 ,   12800, "2017"]

df = pd.DataFrame([a, b], columns = Columns)
df5 = df[2017 - df['Year'].astype(int) <=5]

效果很好,