我很困惑,因为当我删除一行时,但是删除之后我可以继续用df.iloc []来查询该行,但是脚本显示的信息是下一行。

我了解ilow =行索引,但不是,您能向我解释一下错误吗?

例如:

import pandas as pd
import numpy as np

df = pd.DataFrame(np.random.randint(low=0, high=6, size=(10,4)),columns ={'a','b','c','d'})


df

a   b   c   d



0 3 0 4
0 0 1 1
0 1 1 2
1 1 5 5
4 2 3 5
4 2 0 2
2 1 1 4
4 3 2 4
5 2 5 5
2 5 0 0

df.loc [df ['c'] == 5] .index


Int64Index([3,8],dtype ='int64')

df.iloc[3]


1
11
5例
第5天
名称:3,dtype:int64

df = df.drop(df.loc[df['c']==5].index, axis = 0)


df

a   b   c   d



0 3 0 4
0 0 1 1
0 1 1 2
4 2 3 5
4 2 0 2
2 1 1 4
4 3 2 4
2 5 0 0

df.iloc [3]


一个4
b 2
c 3
第5天
名称:4,dtype:int64

在这种情况下,我期待一个例外!

最佳答案

df.loc返回基于标签(索引,列名)的数据。 iloc仅基于从0开始的位置(索引位置,列位置)返回数据。

您的第一行代码是根据条件创建数据框的一部分。 df.index返回切片的索引。

df.loc[df['c']==5].index
Int64Index([3, 8], dtype='int64')


第二行,由于只传递了一个值,因此pandas假定它为索引,并返回指定索引处的所有元素。

df.iloc[3]

a    1
b    1
c    5
d    5


删除索引号3后,由于第4个位置仍然存在,df.iloc [3]将再次返回第4行。另一方面,使用loc会引发keyerror,因为数据帧在数据中不再具有索引号3。

df.loc[3]
KeyError: 'the label [3] is not in the [index]'

09-30 14:31
查看更多