簡體   English   中英

Pandas:如何在不知道列名的情況下為特定值或字符串索引 dataframe

[英]Pandas: how to index dataframe for certain value or string without knowing the column name

雖然這看起來非常有害,但我很難在 dataframe 中隨機獲取某個字符串或值的 dataframe 的索引 position。

我做了一個例子dataframe:

fruits = {
    'column1':["Apples","Pears","Bananas","Oranges","Strawberries"],
    'column2':[1,2,3,4,5],
    'column3':["Kiwis","Mangos","Pineapples","Grapes","Melons"]
          }

df = pd.DataFrame(fruits)

        column1  column2     column3
0        Apples        1       Kiwis
1         Pears        2      Mangos
2       Bananas        3  Pineapples
3       Oranges        4      Grapes
4  Strawberries        5      Melons

現在我想獲取 Mangos 的 position 索引,但不知道它存在於哪一列或哪一行。 到目前為止,我成功地獲得了行索引:

print(df.loc[df.isin(["Mangos"]).any(axis=1)].index)

結果是:

Int64Index([1], dtype='int64')

但現在我還想檢索列索引或列名。

該線程是Get column name 的一個非常簡化的版本,其中值是 pandas dataframe 中的某個值,但我無法使用其他線程找出代碼。

你可以簡單地做:

df.columns[df.isin(['Mangos']).any()])
Index(['column3'], dtype='object')

或者只獲取列名:

df.columns[df.isin(['Mangos']).any()][0]
# column3

要獲取列的索引,請嘗試:

df.columns.get_indexer(df.columns[df.isin(['Mangos']).any()])
# [2]

Stack dataframe重塑成多索引系列,然后使用boolean索引得到索引

s = df.stack()
s[s == 'Mangos'].index

MultiIndex([(1, 'column3')])

您也可以使用np.where

代碼:

import numpy as np
[(df.index[i], df.columns[c]) for i, c in zip(*np.where(df.isin(['Mangos'])))]

Output:

[(1, 'column3')]

您可以自己嘗試一個簡單的搜索。

coordinates = []
indices = df.index
columns = df.columns
for index in indices: # df is the DataFrame
         for col in columns:
             if df[col][index] == 'Mangos':
                 coordinates.append((index, col))
coordinates

Output:

[(1, '第 3 列')]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM