我是Python和Pandas的新手,我正在研究一个示例项目。作为其中的一部分,我正在读取数据帧中的每一行,并确定它应该进入的3个数据帧中的哪一个。我在添加行时得到的结果不一致。有时它会添加行,有时则不添加。我已经尝试了几种不同的方法来添加行,但都取得了有限的成功。我的代码的一部分如下:
#split seed into categories
dfSeedSetosa = dfSeed[dfSeed['Class'] == 'Iris-setosa']
dfSeedVirginica = dfSeed[dfSeed['Class'] == 'Iris-virginica']
dfSeedVersicolor = dfSeed[dfSeed['Class'] == 'Iris-versicolor']
dfSeedSetosa.is_copy = False
dfSeedVirginica.is_copy = False
dfSeedVersicolor.is_copy = False
#calc beginning averages
CalcSetosa()
CalcVirginica()
CalcVersicolor()
#remove seed values from body
dfBody = df[~df.isin(dfSeed)].dropna()
#cycle through the body rows individually, find closest match, add record to appropriate seed, recalc averages
for index, row in dfBody.iterrows():
numSet = abs(numAvgSetSepLen-row['SepalLen'])+abs(numAvgSetSepWid-row['SepalWid'])+abs(numAvgSetPetLen-row['PetalLen'])+abs(numAvgSetPetWid-row['PetalWid'])+abs(numAvgSetSepRat-row['SepalRat'])+abs(numAvgSetPetRat-row['PetalRat'])
numVer = abs(numAvgVerSepLen-row['SepalLen'])+abs(numAvgVerSepWid-row['SepalWid'])+abs(numAvgVerPetLen-row['PetalLen'])+abs(numAvgVerPetWid-row['PetalWid'])+abs(numAvgVerSepRat-row['SepalRat'])+abs(numAvgVerPetRat-row['PetalRat'])
numVir = abs(numAvgVirSepLen-row['SepalLen'])+abs(numAvgVirSepWid-row['SepalWid'])+abs(numAvgVirPetLen-row['PetalLen'])+abs(numAvgVirPetWid-row['PetalWid'])+abs(numAvgVirSepRat-row['SepalRat'])+abs(numAvgVirPetRat-row['PetalRat'])
if numSet < numVer and numSet < numVir:
dfSeedSetosa.loc[len(dfSeedSetosa)] = row
#dfSeedSetosa.append(row, ignore_index=True)
#dfSeedSetosa.ix[len(dfSeedSetosa.index)] = row
CalcSetosa()
elif numVer < numSet and numVer < numVir:
dfSeedVersicolor.loc[len(dfSeedVersicolor)] = row
#dfSeedVersicolor.append(row, ignore_index=True)
#dfSeedVersicolor.ix[len(dfSeedVersicolor.index)] = row
CalcVersicolor()
else:
dfSeedVirginica.loc[len(dfSeedVirginica)] = row
#dfSeedVirginica.append(row,ignore_index=True)
#dfSeedVirginica.ix[len(dfSeedVirginica.index)] = row
CalcVirginica()