【问题标题】:Pandas - find index of value anywhere in DataFramePandas - 在 DataFrame 中的任何位置查找值索引
【发布时间】:2017-07-12 05:10:16
【问题描述】:

我是 Python 和 Pandas 的新手。

我想在我的 pandas 数据框中找到某个值的索引(比如说security_id),因为那是列开始的地方。 (列上方有不相关数据的行数未知,左侧有许多空“列”。)

据我所知,isin 方法只返回一个关于值是否存在的布尔值,而不是它的索引。

如何找到这个值的索引?

【问题讨论】:

标签: python pandas


【解决方案1】:

我认为这个问题可能在here 之前被问过。接受的答案非常全面,应该可以帮助您找到列中值的索引。

编辑: 如果值所在的列未知,则可以使用:

for col in df.columns:
    df[df[col] == 'security_id'].index.tolist()

【讨论】:

  • 在给定的问题中,该列是已知的。就我而言,我不知道值出现在哪一列。但我同意它为我的问题的答案指明了方向
  • 啊,抱歉!您可以遍历数据框中的列并应用上面链接的答案。 for col in df.columns: df[df[col] == 'security_id'].index.tolist()。这也将为您提供您正在寻找的所有内容。
【解决方案2】:

假设您的 DataFrame 如下所示:

      0       1            2      3    4
0     a      er          tfr    sdf   34
1    rt     tyh          fgd    thy  rer
2     1       2            3      4    5
3     6       7            8      9   10
4   dsf     wew  security_id   name  age
5   dfs    bgbf          121  jason   34
6  dddp    gpot         5754   mike   37
7  fpoo  werwrw          342   jack   31

执行以下操作:

for row in range(df.shape[0]): # df is the DataFrame
         for col in range(df.shape[1]):
             if df.get_value(row,col) == 'security_id':
                 print(row, col)
                 break

【讨论】:

  • 谢谢,这似乎是一个解决方案:) 虽然是找到迭代行和列的值的唯一方法吗?有没有更有效的方法?
  • 无论你做什么,都会涉及到迭代。要么你会做,否则 Pandas 会做。将始终涉及内部迭代。此外,迭代停止一次,您将获得 ID。最坏的情况是 security_id 是 DataFrame 的右下角元素( O(mn) )。如果 security_id 位于 DataFrame 的左上半部分,则根本不会花费太多。
  • 此外,您要求进行数据清理。因此,这是一个廉价的预处理步骤。不要试图超优化一切。过早的优化是万恶之源。记住。
  • 是的,这是有道理的,我认为可能是这种情况(无论如何都要迭代)。谢谢你的解释。
【解决方案3】:

您要查找的值不重复:

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')]

你会得到一个列表

【讨论】:

    【解决方案4】:

    避免显式循环的单线解决方案...

    • 返回整行

      df.iloc[np.flatnonzero((df=='security_id').values)//df.shape[1],:]

    • 返回行和列

      df.iloc[ np.flatnonzero((df=='security_id').values)//df.shape[1], np.unique(np.flatnonzero((df=='security_id').values)%df.shape[1]) ]

    【讨论】:

      【解决方案5】:

      获取所有列中与搜索词匹配的行的索引

      search = 'security_id' 
      df.loc[df.isin([search]).any(axis=1)].index.tolist()
      

      在所有列中过滤匹配搜索词的行

      search = 'search term' 
      df.loc[df.isin([search]).any(axis=1)]
      

      【讨论】:

      • 这可能是最高效的答案,因为它使用.loc。很好的答案!
      【解决方案6】:

      函数查找数据帧中值的位置

      import pandas as pd
      import numpy as np
      
      def pandasFindPositionsInDataframe(dfIn,findme):
          positions = []
          irow =0
          while ( irow < len(dfIn.index)):
              list_colPositions=dfIn.columns[dfIn.iloc[irow,:]==findme].tolist()   
              if list_colPositions != []:
                  colu_iloc = dfIn.columns.get_loc(list_colPositions[0])
                  positions.append([irow, colu_iloc])
              irow +=1
      
          return positions
      

      【讨论】:

      • 如何做到不区分大小写?
      猜你喜欢
      • 2014-11-26
      • 2019-05-27
      • 2017-04-30
      • 1970-01-01
      • 2016-10-06
      • 2013-02-15
      • 2018-03-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多