51

I have the following DataFrame:

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

As you can see, column b is used as an index. I want to get the ordinal number of the row fulfilling ('b' == 5), which in this case would be 1.

The column being tested can be either an index column (as with b in this case) or a regular column, e.g. I may want to find the index of the row fulfilling ('c' == 6).

4

3 回答 3

63

请改用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
于 2016-02-01T19:35:48.007 回答
51

你可以像这样使用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]

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

于 2013-08-13T01:38:30.673 回答
10

使用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
于 2018-10-23T15:11:24.490 回答