单个位置索引器越界遍历pandas datafram

2024-10-01 11:19:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个dataframe,myDF,我希望将其中的一列设置为0,使用其他列的条件组合,并使用第二个dataframe criteriaDF建立索引。在

在我的头():

       DateTime  GrossPowerMW USDateTime_string  DateTime_timestamp  \
0  01/01/1998 00:00        17.804  01/01/1998 00:00 1998-01-01 00:00:00   
1  01/01/1998 01:00        18.751  01/01/1998 01:00 1998-01-01 01:00:00   
2  01/01/1998 02:00        20.501  01/01/1998 02:00 1998-01-01 02:00:00   
3  01/01/1998 03:00        22.222  01/01/1998 03:00 1998-01-01 03:00:00   
4  01/01/1998 04:00        24.437  01/01/1998 04:00 1998-01-01 04:00:00   

   Month  Day  Hour  GrossPowerMW_Shutdown  
0      1    3     0                 17.804  
1      1    3     1                 18.751  
2      1    3     2                 20.501  
3      1    3     3                 22.222  
4      1    3     4                 24.437  

标准:

^{pr2}$

然后,myDF通过以下for循环运行:

month = 1
for month in range (1, 13):
    shutdown_hours = range(int(criteriaDF.iloc[month]['STARTTIME']), int(criteriaDF.iloc[month]['ENDTIME']))
    myDF.loc[(myDF["Month"].isin([month])) & (myDF["Hour"].isin(shutdown_hours)) & (myDF["Day"].isin(shutdown_days)), "GrossPowerMW_Shutdown"] *= 0
    month = month + 1

这将产生以下错误:

Traceback (most recent call last):

File "", line 1, in runfile('myscript.py', wdir='C:myscript')

File "C:\ProgramData\Anaconda2\lib\site-packages\spyder\utils\site\sitecustomize.py", line 880, in runfile execfile(filename, namespace)

File "C:\ProgramData\Anaconda2\lib\site-packages\spyder\utils\site\sitecustomize.py", line 87, in execfile exec(compile(scripttext, filename, 'exec'), glob, loc)

File "myscript.py", line 111, in gross_yield, curtailed_yield, shutdown_loss, df_testing = calculate_loss(input_file, input_shutdownbymonth, shutdown_days) #Returning df for testing/interrogation only. Delete once finished.

File "myscript.py", line 79, in calculate_loss shutdown_hours = range(int(criteriaDF.iloc[month]['STARTTIME']), int(criteriaDF.iloc[month]['ENDTIME']))

File "C:\ProgramData\Anaconda2\lib\site-packages\pandas\core\indexing.py", line 1328, in __getitem__ return self._getitem_axis(key, axis=0)

File "C:\ProgramData\Anaconda2\lib\site-packages\pandas\core\indexing.py", line 1749, in _getitem_axis self._is_valid_integer(key, axis)

File "C:\ProgramData\Anaconda2\lib\site-packages\pandas\core\indexing.py", line 1638, in _is_valid_integer raise IndexError("single positional indexer is out-of-bounds")

IndexError: single positional indexer is out-of-bounds

但是如果我设置

month = 0
for month in range (0, 12)

但是,这与我的dataframe在列['Month']上的索引不匹配,该列运行1-12而不是0->;11。在

为了证实我的理解

range (1, 13)

退货

[1,2,3,4,5,6,7,8,9,10,11,12].

我还尝试过用for循环中month=12的代码逐行手动运行代码。所以我不确定为什么在rage中使用month(1,13)不起作用,注意到12是列表范围(1,13)中的最高整数。在

我的代码或方法有什么错误?在


Tags: inpyforlibpackageslinesiterange
1条回答
网友
1楼 · 发布于 2024-10-01 11:19:54

您使用的是^{},这是“基于位置的纯整数位置索引”,因此它只计算从0到11的行数 您应该使用^{},它可以查看索引的值(从1到12)

相关问题 更多 >