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

Dun*_*eal 32 python numpy pandas

我有以下DataFrame:

   a  b  c
b
2  1  2  3
5  4  5  6
Run Code Online (Sandbox Code Playgroud)

如您所见,列b用作索引.我希望得到行的序数,('b' == 5)这种情况就是这样1.

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

hli*_*117 36

请改用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
Run Code Online (Sandbox Code Playgroud)

  • 这不是OP想要的.您正在回答这个问题,"给定索引的序数位置是多少?".OP想要知道,"满足给定条件的行的序数位置是多少?".也就是说,输入是特定条件,例如(df.b == 5)或(df.c == 6). (7认同)

unu*_*tbu 34

你可以像这样使用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]
Run Code Online (Sandbox Code Playgroud)

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

  • 而不是做`np.where(df.index == 5)[0]`,pandas有一个`get_loc`函数,它似乎更犹豫不决.http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Index.get_loc.html (11认同)
  • @hlin117 - 您的评论应该是正确答案,请添加 (2认同)

Gab*_*cco 9

使用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
Run Code Online (Sandbox Code Playgroud)