Python >> Tutoriel Python >  >> Python Tag >> Pandas

Pandas comment trouver la colonne contient une certaine valeur

Dans ce tutoriel, nous allons apprendre à trouver l'index d'une colonne qui contient une certaine valeur.

Exemple, nous avons un dataframe avec les colonnes suivantes :

import pandas as pd
df = pd.DataFrame({
    'A': [1, 4, 7, 1, 4],
    'B': [2, 5, 8, 2, 5],
    'C': [3, 6, 9, 3, 6]
})
    A   B   C
0   1   2   3
1   4   5   6
2   7   8   9
4   1   2   3
5   4   5   6

Trouvons l'index de la colonne qui contient la valeur 5 .

Utilisation de np.where à partir de numpy

La fonction numpy np.where peut être utilisé pour trouver l'index d'une colonne qui contient une certaine valeur. La syntaxe est :numpy.where(condition[, x, y])

Parameters
conditionarray_like, bool
Where True, yield x, otherwise yield y.

x, y: array_like
Values from which to choose. x, y and condition need to be broadcastable to some shape.

Returns
out: ndarray
An array with elements from x where condition is True, and elements from y elsewhere.

Pour l'exemple ci-dessus, nous pouvons utiliser le code suivant pour trouver l'index de la colonne B qui contient la valeur 5 .

import numpy as np
col_index = pd.DataFrame(np.where(df.eq(5))[1] + 1, columns=['col_index'])

Sortie :

   col_index
0          2
1          2