简体   繁体   English

Pandas 数据帧产生 KeyError: -1

[英]Pandas dataframe yields KeyError: -1

I got the error KeyError: -1 on the following code:我在以下代码中收到错误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)

This is a pandas dataframe, where I try to print out the list of indexes [i] which are bigger than the previous index [i-1].这是一个 Pandas 数据框,我尝试打印出比前一个索引 [i-1] 大的索引列表 [i]。 But it doesn't work, and I don't know what I am doing wrong.但它不起作用,我不知道我做错了什么。

When you start the loop, i equals 0 , so i-1 equals -1 , which probably isn't in your index.当您开始循环时, i等于0 ,因此i-1等于-1 ,这可能不在您的索引中。

You could try你可以试试

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)

don't use loops you're losing the core functionality of pandas which is to take advantage of vectorised solutions.不要使用循环,你会失去 Pandas 的核心功能,即利用矢量化解决方案。

we can use shift and .tolist to grab your desired result.我们可以使用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

The reason might lie in the fact that the index of your data frame may not be perfectly ordered from 0 to range(df).原因可能在于您的数据框的索引可能没有从 0 到 range(df) 完美排序。 That is, your index may not necessarily be 1, 2, 3, 4,..., N. If your index is something like this:也就是说,您的索引可能不一定是 1、2、3、4、...、N。如果您的索引是这样的:

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

Then, when you run the for loop , you will get this error.然后,当您运行for 循环时,您将收到此错误。 You might wanna try this first:你可能想先试试这个:

df = df.reset_index()

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

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