Python Pandas DataFrame iloc索引报错:非整数键问题修复
错误信息
/usr/local/lib/python3.10/dist-packages/pandas/core/indexing.py in _getitem_axis(self, key, axis) 1620 key = item_from_zerodim(key) 1621 if not is_integer(key):
-> 1622 raise TypeError("Cannot index by location index with a non-integer key") 1623 1624 # validate the locationTypeError: Cannot index by location index with a non-integer key
错误出现在代码行 data.iloc[[x]["Date"]] == "1/9/"+str(year)+"12:00:00",尝试多种方案无效,求修复方法。
相关代码
#Calculate the cost, revenue, and profit for each day in each year. def calculateParametersOnedayEachMonth(ptype,month, year): price = 0 r = 0 data = pd.DataFrame(readData) #print(data[["Date"]]) for x in range(data.size): #print(x) if data.iloc[[x]["Date"]] == "1/"+month+"/"+str(year)+"12:00:00" : print("I am inside") index1 = x index2 = x+24 for index1 in range(index2): if type == "PV": price = price + data.iloc[[index1]['PVPrice']] print(price) loadForcast = data.iloc[[index1]['PVLoadForecast']] powerForcast = data.iloc[[index1]['PVPowerForecast']] r = r+(loadForcast-powerForcast) print(r) elif type == "DG": price = price + data.iloc[[index1]['DGPrices']] loadForcast = data.iloc[[index1]['DGLoad forecast']] powerForcast = data.iloc[[index1]['DGPowerForecast']] r = r+(loadForcast-powerForcast) elif type == "Wind": price = price + data.iloc[[index1]['WPrice']] loadForcast = data.iloc[[index1]['WindLoadforecast']] powerForcast = data.iloc[[index1]['WindPowerForecast']] r = r+(loadForcast-powerForcast) elif type == "BES": price = price + data.iloc[[index1]['BESPrice']] loadForcast = data.iloc[[index1]['BESLoadForecast']] powerForcast = data.iloc[[index1]['BESPowerForecast']] r = r+(loadForcast-powerForcast) elif type == "Zonal": price = price + data.iloc[[index1]['ZonalPrice']] loadForcast = data.iloc[[index1]['ZonalLoadForecast']] powerForcast = data.iloc[[index1][' ZonalPowerForecast']] r = r+(loadForcast-powerForcast) else: print("Sorry, this type is not provided by dataset") break avgPrice = price / 24 avgRevenue = r/24 print("Day-Ahead Energy Price",avgPrice) print("Day-Ahead Revenue",avgPrice) allValues = { "Cost": avgPrice , "Reveneu": avgRevenue} if type=="PV": if year == "2011": listAllDaysParameters2011_PV.append(allValues) elif year == "2012": listAllDaysParameters2012_PV.append(allValues) elif year == "2013": listAllDaysParameters2013_PV.append(allValues) elif year == "2014": listAllDaysParameters2014_PV.append(allValues) elif year == "2015": listAllDaysParameters2015_PV.append(allValues) elif year == "2016": listAllDaysParameters2016_PV.append(allValues) else: print("This year is not provided by the dataset") elif type=="DG": if year == 2011: listAllDaysParameters2011_DG.append(allValues) elif year == 2012: listAllDaysParameters2012_DG.append(allValues) elif year == 2013: listAllDaysParameters2013_DG.append(allValues) elif year == 2014: listAllDaysParameters2014_DG.append(allValues) elif year == 2015: listAllDaysParameters2015_DG.append(allValues) elif year == 2016: listAllDaysParameters2016_DG.append(allValues) else: print("This year is not provided by the dataset") elif type=="Wind": if year == 2011: listAllDaysParameters2011_Wind.append(allValues) elif year == 2012: listAllDaysParameters2012_Wind.append(allValues) elif year == 2013: listAllDaysParameters2013_Wind.append(allValues) elif year == 2014: listAllDaysParameters2014_Wind.append(allValues) elif year == 2015: listAllDaysParameters2015_Wind.append(allValues) elif year == 2016: listAllDaysParameters2016_Wind.append(allValues) else: print("This year is not provided by the dataset") elif type=="BES": if year == 2011: listAllDaysParameters2011_BES.append(allValues) elif year == 2012: listAllDaysParameters2012_BES.append(allValues) elif year == 2013: listAllDaysParameters2013_BES.append(allValues) elif year == 2014: listAllDaysParameters2014_BES.append(allValues) elif year == 2015: listAllDaysParameters2015_BES.append(allValues) elif year == 2016: listAllDaysParameters2016_BES.append(allValues) else: print("This year is not provided by the dataset") elif type=="Zonal": if year == 2011: listAllDaysParameters2011_Zonal.append(allValues) elif year == 2012: listAllDaysParameters2012_Zonal.append(allValues) elif year == 2013: listAllDaysParameters2013_Zonal.append(allValues) elif year == 2014: listAllDaysParameters2014_Zonal.append(allValues) elif year == 2015: listAllDaysParameters2015_Zonal.append(allValues) elif year == 2016: listAllDaysParameters2016_Zonal.append(allValues) else: print("Sorry, this year is not provided by the dataset") else: print("Sorry, this type is not provided by the dataset")
1. 修正iloc的核心语法错误
你写的 data.iloc[[x]["Date"]] 完全不符合Pandas索引规则:
iloc是位置索引,只能接受整数、整数列表或切片,不能直接用列名[x]["Date"]语法错误,x是整数,无法从整数中取"Date"键
正确写法是先按位置取行,再取列:
data.iloc[x]["Date"] # 更高效的写法:先取列再按位置索引 data["Date"].iloc[x]
同时日期字符串缺少空格,修正后的错误行应为:
if data.iloc[x]["Date"] == f"1/{month}/{year} 12:00:00":
2. 批量修正所有iloc错误用法
代码中所有类似 data.iloc[[index1]['PVPrice']] 的写法都要调整,比如:
# 错误写法 price = price + data.iloc[[index1]['PVPrice']] # 正确写法 price = price + data.iloc[index1]['PVPrice'] # 或更高效的写法 price = price + data['PVPrice'].iloc[index1]
3. 修复变量名冲突
函数参数是ptype,但代码里全用了type,这会覆盖Python内置的type()函数,导致逻辑错误。所有if type == "PV"这类语句都要改成if ptype == "PV"。
4. 细节修正
- 打印
avgRevenue时误写为avgPrice,修正为:print("Day-Ahead Revenue", avgRevenue) - 字典键拼写错误:
"Reveneu"改为"Revenue" - 注意列名空格问题,比如
" ZonalPowerForecast"要和实际数据列名完全一致,避免取值失败
5. 可选:优化循环逻辑(更符合Pandas风格)
用for x in range(data.size)遍历行效率极低,建议用Pandas向量化操作替代:
# 先把Date列转为datetime类型,避免字符串匹配问题 data['Date'] = pd.to_datetime(data['Date']) # 构造目标日期 target_date = pd.to_datetime(f"{year}-{month}-01 12:00:00") # 找到匹配行的索引 match_row = data[data['Date'] == target_date].index[0] # 直接取后续24行数据 subset = data.iloc[match_row:match_row+24]
这样可以完全替代外层for循环,代码更简洁高效。
内容的提问来源于stack exchange,提问作者Esra

