获取满足条件的Pandas数据帧行的整数索引?

2024-05-20 02:31:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下数据框:

   a  b  c
b
2  1  2  3
5  4  5  6

如您所见,列b用作索引。我想得到满足('b' == 5)的行的序号,在本例中是1

正在测试的列可以是索引列(在本例中是b)或常规列,例如,我可能希望找到满足('c' == 6)的行的索引。


Tags: 数据常规本例序号
3条回答

你可以这样使用np.where

import pandas as pd
import numpy as np
df = pd.DataFrame(np.arange(1,7).reshape(2,3),
                  columns = list('abc'), 
                  index=pd.Series([2,5], name='b'))
print(df)
#    a  b  c
# b         
# 2  1  2  3
# 5  4  5  6
print(np.where(df.index==5)[0])
# [1]
print(np.where(df['c']==6)[0])
# [1]

返回的值是一个数组,因为一列中可能有多个具有特定索引或值的行。

改用Index.get_loc

重用@unutbu的设置代码,您将获得相同的结果。

>>> import pandas as pd
>>> import numpy as np


>>> df = pd.DataFrame(np.arange(1,7).reshape(2,3),
                  columns = list('abc'),
                  index=pd.Series([2,5], name='b'))
>>> df
   a  b  c
b
2  1  2  3
5  4  5  6
>>> df.index.get_loc(5)
1

Index.get_loc和一般条件:

>>> import pandas as pd
>>> import numpy as np


>>> df = pd.DataFrame(np.arange(1,7).reshape(2,3),
                  columns = list('abc'),
                  index=pd.Series([2,5], name='b'))
>>> df
   a  b  c
b
2  1  2  3
5  4  5  6
>>> df.index.get_loc(df.index[df['b'] == 5][0])
1

相关问题 更多 >