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

前端 未结 5 571
一生所求
一生所求 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:29

    The other way around using 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]
    

提交回复
热议问题