df.loc在切片器返回nan中使用索引

2024-09-25 12:23:53 发布

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

我试图迭代一个日期框并获得某些行之间的最大列数,问题是当我将索引值放在我得到的nan上时:

for index, row in df.iterrows():
        if index >= 51:
            print(df.loc[index:(index - 51), 'close'].max())

为此,我得到一个nan值。
但如果我在切片器中使用如下数字:

for index, row in df.iterrows():
        if index >= 51:
            print(df.loc[0:51, 'close'].max())

我会得到的结果不是我需要的,因为我需要它是一个移动的窗口,但这只是为了显示问题

你知道为什么它不接受索引作为有效的切片器吗


Tags: indfforcloseindexif切片数字
1条回答
网友
1楼 · 发布于 2024-09-25 12:23:53

我认为问题在于loc索引片向后,导致没有返回任何内容;在第一次迭代中,您的切片是df.loc[51:0, 'close'].max()。相反:

for index, row in df.iterrows():
    if index >= 51:
        print(df.loc[index-51:index,'close'].max())

#first iteration: df.loc[0:51,'close']

我假设索引是整数/数字,因此为什么可以使用loc混合整数和列名?否则我认为iloc可以工作


修正案:这是我用iloc所想的,但(在我看来)与你的方法没有什么不同:

close_iloc = df.columns.get_loc('close') #gets the integer number needed for iloc to reference 'close'
for i in range(len(df.index)):
    if i >= 51:
        print(df.iloc[i-51:i,close_iloc].max())

相关问题 更多 >