繁体   English   中英

Pandas 数据帧产生 KeyError: -1

[英]Pandas dataframe yields KeyError: -1

我在以下代码中收到错误KeyError: -1

u = []

for i in range(len(df['Some column'])):
   if df['Some column'][i] > df['Some column'][i-1]:
      u.append(df['Some column'][i])

print(u)

这是一个 Pandas 数据框,我尝试打印出比前一个索引 [i-1] 大的索引列表 [i]。 但它不起作用,我不知道我做错了什么。

当您开始循环时, i等于0 ,因此i-1等于-1 ,这可能不在您的索引中。

你可以试试

u = []

for i in range(1, len(df['Some column'])):
   if df['Some column'][i] > df['Some column'][i-1]:
      u.append(df['Some column'][i])

print(u)

不要使用循环,你会失去 Pandas 的核心功能,即利用矢量化解决方案。

我们可以使用shift.tolist来获取您想要的结果。

import numpy as np
import pandas as pd

np.random.seed(50)

df = pd.DataFrame({'data' : np.random.randint(0,500,size=500)})

u = df.loc[df['data'] > df['data'].shift(-1)]['data'].tolist()

print(u)
out:
[480, 289, 478, 229, 278, 258, ...]
len(u)
out:
244

原因可能在于您的数据框的索引可能没有从 0 到 range(df) 完美排序。 也就是说,您的索引可能不一定是 1、2、3、4、...、N。如果您的索引是这样的:

1, 2, 30, 34, 45, 48, 50

然后,当您运行for 循环时,您将收到此错误。 你可能想先试试这个:

df = df.reset_index()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM