获取一个pandas数据帧的行的索引作为整数

时间:2016-12-19 07:00:02

标签: python pandas numpy

假设一个简单的数据框,例如

    A         B
0   1  0.810743
1   2  0.595866
2   3  0.154888
3   4  0.472721
4   5  0.894525
5   6  0.978174
6   7  0.859449
7   8  0.541247
8   9  0.232302
9  10  0.276566

在给定条件的情况下,如何检索行的索引值? 例如: dfb = df[df['A']==5].index.values.astype(int) 返回[4],但我想要的只是4。这导致我在代码中遇到麻烦。

基于某些条件,我希望记录满足该条件的索引,然后选择之间的行。

我试过

dfb = df[df['A']==5].index.values.astype(int)
dfbb = df[df['A']==8].index.values.astype(int)
df.loc[dfb:dfbb,'B']

获得所需的输出

    A         B
4   5  0.894525
5   6  0.978174
6   7  0.859449

但我得到TypeError: '[4]' is an invalid key

4 个答案:

答案 0 :(得分:26)

更容易添加{ "compilerOptions": { "module": "commonjs", "target": "es6", "moduleResolution": "node", "baseUrl": "src", "removeComments": true, "allowSyntheticDefaultImports": true, "noImplicitAny": false, "sourceMap": true, "jsx": "react", "experimentalDecorators": true, "noLib": false, "declaration": false }, "exclude": [ "node_modules" ] } - 使用一个元素选择列表的第一个值:

[0]
dfb = df[df['A']==5].index.values.astype(int)[0]
dfbb = df[df['A']==8].index.values.astype(int)[0]

然后似乎需要减去dfb = int(df[df['A']==5].index[0]) dfbb = int(df[df['A']==8].index[0])

1

boolean indexingquery的另一种解决方案:

print (df.loc[dfb:dfbb-1,'B'])
4    0.894525
5    0.978174
6    0.859449
Name: B, dtype: float64
print (df[(df['A'] >= 5) & (df['A'] < 8)])
   A         B
4  5  0.894525
5  6  0.978174
6  7  0.859449

print (df.loc[(df['A'] >= 5) & (df['A'] < 8), 'B'])
4    0.894525
5    0.978174
6    0.859449
Name: B, dtype: float64

答案 1 :(得分:21)

要回答有关如何将索引作为所需选择的整数的原始问题,以下内容将起作用:

df[df['A']==5].index.item()

答案 2 :(得分:4)

想要包含A == 5行和所有行但的行的性质,包括A == 8表示我们最终会使用iloc的行(loc包括切片的两端。)

为了获取索引标签,我们使用idxmax。这将返回最大值的第一个位置。我在一个布尔系列上运行它,其中A == 5(然后当A == 8)返回首次发生A == 5时的索引值(A == 8同样的事情)。

然后我使用searchsorted来查找索引标签(我在上面找到)所在位置的序数位置。这就是我在iloc中使用的内容。

i5, i8 = df.index.searchsorted([df.A.eq(5).idxmax(), df.A.eq(8).idxmax()])
df.iloc[i5:i8]

enter image description here

numpy

你可以通过使用类似numpy函数的底层numpy对象来进一步增强这一点。我把它包装成一个方便的功能。

def find_between(df, col, v1, v2):
    vals = df[col].values
    mx1, mx2 = (vals == v1).argmax(), (vals == v2).argmax()
    idx = df.index.values
    i1, i2 = idx.searchsorted([mx1, mx2])
    return df.iloc[i1:i2]

find_between(df, 'A', 5, 8)

enter image description here

<强> 定时
enter image description here

答案 3 :(得分:1)

关于按行搜索的小总结:

如果您不知道列值或列具有非数字值,这将很有用

如果您希望将索引号作为整数获取,您也可以这样做:

item = df[4:5].index.item()
print(item)
4

它也适用于numpy / list:

numpy = df[4:7].index.to_numpy()[0]
lista = df[4:7].index.to_list()[0]

在[x]中,您选择[4:7]范围内的数字,例如,如果您想要6:

numpy = df[4:7].index.to_numpy()[2]
print(numpy)
6

对于DataFrame:

df[4:7]

    A          B
4   5   0.894525
5   6   0.978174
6   7   0.859449

或:

df[(df.index>=4) & (df.index<7)]

    A          B
4   5   0.894525
5   6   0.978174
6   7   0.859449