小编典典

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

python

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

    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) return
[4],但是我想得到的只是just 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


阅读 147

收藏
2020-12-20

共1个答案

小编典典

添加起来更容易[0]-使用一个元素选择list的第一个值:

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])

但是,如果某些值不匹配,则会出现错误,因为第一个值不存在。

解决方案是使用nextiter用于获取缺省parameetr如果没有匹配的值:

dfb = next(iter(df[df['A']==5].index), 'no match')
print (dfb)
4

dfb = next(iter(df[df['A']==50].index), 'no match')
print (dfb)
no match

然后似乎需要减去1

print (df.loc[dfb:dfbb-1,'B'])
4    0.894525
5    0.978174
6    0.859449
Name: B, dtype: float64

boolean indexing或的另一种解决方案query

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

print (df.query('A >= 5 and A < 8'))
   A         B
4  5  0.894525
5  6  0.978174
6  7  0.859449
2020-12-20