【问题标题】:In PANDAS, how to get the index of a known value?在PANDAS中,如何获取已知值的索引?
【发布时间】:2013-05-17 00:41:23
【问题描述】:

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

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
........

众所周知,我们可以通过它对应的索引来获取一个值,像这样。

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

但是如何按值获取索引呢?

【问题讨论】:

    标签: indexing pandas


    【解决方案1】:

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

    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]
    

    【讨论】:

    • 一个索引可以有非唯一的条目,为什么你说返回一个列表更有意义?
    • 嗯,我觉得是我的错。如果所有索引都是唯一的,我们可以通过a.c1[a.c1 == 8].index.tolist()[0]得到单个索引
    • 感谢您的回答,这是一个很好的理想。我没有考虑索引对象可以转换为普通列表。再次感谢。
    • @waitingkuo 是他们在 2017 年发布的任何复杂的获取索引的方法吗?
    • @waitingkuo 如果我们想插入两个条件,我们该怎么做?像 a.c1[a.c1 == 8 ]。不适用于此示例,但想象一下 a.c2 == 10 是否也存在
    【解决方案2】:

    使用 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]
    

    【讨论】:

      【解决方案3】:

      使用 .loc[] 访问器:

      In [25]: a.loc[a['c1'] == 8].index[0]
      Out[25]: 4
      

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

      In [17]: a.set_index('c1').index.get_loc(8)
      Out[17]: 4
      

      【讨论】:

        【解决方案4】:

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

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

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

        如果查询返回多于一行,则可以通过指定所需的索引来访问附加的索引结果,例如.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 
        

        【讨论】:

          【解决方案5】:

          我认为这可能对您有所帮助,索引和值的列。

          您要查找的值不重复

          poz=matrix[matrix==minv].dropna(axis=1,how='all').dropna(how='all')
          value=poz.iloc[0,0]
          index=poz.index.item()
          column=poz.columns.item()
          

          你可以得到它的索引和列

          重复:

          matrix=pd.DataFrame([[1,1],[1,np.NAN]],index=['q','g'],columns=['f','h'])
          matrix
          Out[83]: 
             f    h
          q  1  1.0
          g  1  NaN
          poz=matrix[matrix==minv].dropna(axis=1,how='all').dropna(how='all')
          index=poz.stack().index.tolist()
          index
          Out[87]: [('q', 'f'), ('q', 'h'), ('g', 'f')]
          

          你会得到一个列表

          【讨论】:

            猜你喜欢
            • 2021-12-06
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2022-11-03
            • 2017-10-12
            • 2016-10-15
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多