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

2024-06-06 05:04:25 发布

您现在位置: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) 返回[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


Tags: 数据代码andfindexis记录条件
3条回答

要回答关于如何将索引作为所需选择的整数的原始问题,请执行以下操作:

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

想要包含A == 5的行和所有到但不包括A == 8的行的性质意味着我们最终将使用ilocloc包括切片的两端)。

为了得到索引标签,我们使用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

更简单的方法是添加[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])

但如果可能,某些值不匹配,则会引发错误,因为第一个值不存在。

如果值不匹配,则将nextiter一起用于获取默认参数:

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

使用^{}^{}的另一个解决方案:

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

相关问题 更多 >