2
votes

Comment extraire l'index de colonne et de ligne d'un bloc de données qui satisfait à une condition

Je voudrais stocker toutes les "coordonnées" (positions des colonnes et positions des lignes), de toutes les entrées Dataframe qui remplissent une certaine condition. Dans mon cas, si les valeurs sont supérieures à 0,8.

Voici mon code:

import numpy as np
import pandas as pd


randValues = np.random.rand(5,5)

df = pd.DataFrame(randValues)
df_bool = df > 0.8


colArray = np.empty([])
rowArray = np.empty([])


for dfIdx, dfCol in enumerate(df_bool):
    row = dfCol.loc[dfCol['1'] == True]

    if ~row.isempty():
        colArray.append(dfIdx)
        rowArray.append(row)


0 commentaires

3 Réponses :


1
votes

Utilisez numpy.where pour les positions, puis sélectionnez en indexant sinon les valeurs d'index / colonnes par défaut:

np.random.seed(2019)
randValues = np.random.rand(5,5)

df = pd.DataFrame(randValues, columns=list('abcde'))
print (df)
          a         b         c         d         e
0  0.903482  0.393081  0.623970  0.637877  0.880499
1  0.299172  0.702198  0.903206  0.881382  0.405750
2  0.452447  0.267070  0.162865  0.889215  0.148476
3  0.984723  0.032361  0.515351  0.201129  0.886011
4  0.513620  0.578302  0.299283  0.837197  0.526650

r, c = np.where(df > 0.8)
print (r)
[0 0 1 1 2 3 3 4]
print (c)
[0 4 2 3 3 0 4 3]

colArray = df.columns.values[c]
print (colArray)
['a' 'e' 'c' 'd' 'd' 'a' 'e' 'd']

rowArray = df.index.values[c]
print (rowArray)
[0 4 2 3 3 0 4 3]


0 commentaires


0
votes

Utilisez np.where avec np.column_stack:

array([0,2],
      [1,3])

Output:

randValues = np.random.rand(5,5)

df = pd.DataFrame(randValues)
df_bool = df > 0.8

ind = np.column_stack(np.where(df_bool)))
print(ind)
colArray = [i[1] for i in ind]    # [2,3]
rowArray = [i[0] for i in ind]    # [0,1]


0 commentaires