In PANDAS, how to get the index of a known value?

前端 未结 5 572
一生所求
一生所求 2021-01-30 01:41

If we have a known value in a column, how can we get its index-value? For example:

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


        
5条回答
  •  温柔的废话
    2021-01-30 02:27

    To get the index by value, simply add .index[0] to the end of a query. This will return the index of the first row of the result...

    So, applied to your dataframe:

    In [1]: a[a['c2'] == 1].index[0]     In [2]: a[a['c1'] > 7].index[0]   
    Out[1]: 0                            Out[2]: 4                         
    

    Where the query returns more than one row, the additional index results can be accessed by specifying the desired index, e.g. .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 
    

提交回复
热议问题