在PANDAS中,如何获得已知值的索引?

use*_*991 23 indexing pandas

如果我们在列中有一个已知值,我们如何获得其索引值?例如:

In [148]: a = pd.DataFrame(np.arange(10).reshape(5,2),columns=['c1','c2'])
In [149]: a
Out[149]:   
   c1  c2
0   0   1
1   2   3
2   4   5
........
Run Code Online (Sandbox Code Playgroud)

我们知道,我们可以通过与之对应的索引获取值,就像这样.

In [151]: a.ix[0,1]    In [152]: a.c2[0]   In [154]: a.c2.ix[0]   <--  use index
Out[151]: 1            Out[152]: 1         Out[154]: 1            <--  get value
Run Code Online (Sandbox Code Playgroud)

但是如何按价值获得指数?

wai*_*kuo 34

您的值可能有多个索引映射,返回列表更有意义:

In [48]: a
Out[48]: 
   c1  c2
0   0   1
1   2   3
2   4   5
3   6   7
4   8   9

In [49]: a.c1[a.c1 == 8].index.tolist()
Out[49]: [4]
Run Code Online (Sandbox Code Playgroud)

  • 嗯,我觉得是我的错。如果所有索引都是唯一的,我们可以通过`a.c1[a.c1 == 8].index.tolist()[0]`得到单个索引 (3认同)

gxp*_*xpr 12

使用.loc []访问器:

In [25]: a.loc[a['c1'] == 8].index[0]
Out[25]: 4
Run Code Online (Sandbox Code Playgroud)

也可以通过将'c1'设置为索引来使用get_loc().这不会改变原始数据帧.

In [17]: a.set_index('c1').index.get_loc(8)
Out[17]: 4
Run Code Online (Sandbox Code Playgroud)


Sur*_*rya 6

使用numpy.where()的另一种方法:

import numpy as np
import pandas as pd

In [800]: df = pd.DataFrame(np.arange(10).reshape(5,2),columns=['c1','c2'])

In [801]: df
Out[801]: 
   c1  c2
0   0   1
1   2   3
2   4   5
3   6   7
4   8   9

In [802]: np.where(df["c1"]==6)
Out[802]: (array([3]),)

In [803]: indices = list(np.where(df["c1"]==6)[0])

In [804]: df.iloc[indices]
Out[804]: 
   c1  c2
3   6   7

In [805]: df.iloc[indices].index
Out[805]: Int64Index([3], dtype='int64')

In [806]: df.iloc[indices].index.tolist()
Out[806]: [3]
Run Code Online (Sandbox Code Playgroud)


Rum*_*ish 5

要按值获取索引,只需将.index[0]添加 到查询的末尾。这将返回结果第一行的索引...

因此,应用于您的数据框:

In [1]: a[a['c2'] == 1].index[0]     In [2]: a[a['c1'] > 7].index[0]   
Out[1]: 0                            Out[2]: 4                         
Run Code Online (Sandbox Code Playgroud)

在查询返回多于一行的情况下,可以通过指定所需的索引来访问额外的索引结果,例如.index[n]

In [3]: a[a['c2'] >= 7].index[1]     In [4]: a[(a['c2'] > 1) & (a['c1'] < 8)].index[2]  
Out[3]: 4                            Out[4]: 3 
Run Code Online (Sandbox Code Playgroud)