logo

Pandas DataFrame.loc[]

El DataFrame.loc[] s'utilitza per recuperar el grup de files i columnes mitjançant etiquetes o una matriu booleana al DataFrame. Només pren etiquetes d'índex i, si existeix al DataFrame que truca, retorna les files, columnes o DataFrame.

El DataFrame.loc[] es basa en una etiqueta, però es pot utilitzar amb la matriu booleana.

Les entrades permeses per .lloc[] són:

  • Etiqueta única, p. ex., 7 o a . Aquí, 7 s'interpreta com l'etiqueta de l'índex.
  • Llista o matriu d'etiquetes, p. ['x', 'y', 'z'].
  • Tallar l'objecte amb etiquetes, p. 'x':'f'.
  • Una matriu booleana de la mateixa longitud. per exemple. [Veritat, veritat, fals].
  • cridablefunció amb un argument.

Sintaxi

 pandas.DataFrame.loc[] 

Paràmetres

Cap

Devolucions

Retorna escalar, sèrie o DataFrame.

Exemple

# importar pandes com a pd

 import pandas as pd # Creating the DataFrame info = pd.DataFrame({'Age':[32, 41, 44, 38, 33], 'Name':['Phill', 'William', 'Terry', 'Smith', 'Parker']}) # Create the index index_ = ['Row_1', 'Row_2', 'Row_3', 'Row_4', 'Row_5'] # Set the index info.index = index_ # return the value final = info.loc['Row_2', 'Name'] # Print the result print(final) 

Sortida:

 William 

Exemple 2:

 # importing pandas as pd import pandas as pd # Creating the DataFrame info = pd.DataFrame({'P':[28, 17, 14, 42, None], 'Q':[15, 23, None, 15, 12], 'R':[11, 23, 16, 32, 42], 'S':[41, None, 34, 25, 18]}) # Create the index index_ = ['A', 'B', 'C', 'D', 'E'] # Set the index info.index = index_ # Print the DataFrame print(info) 

Sortida:

 P Q R S A 28.0 15.0 11 41.0 B 17.0 23.0 23 NaN C 14.0 NaN 16 34.0 D 42.0 15.0 32 25.0 E NaN 12.0 42 18.0 

Ara, hem d'utilitzar DataFrame.loc atribut per retornar els valors presents al DataFrame.

 # return the values result = info.loc[:, ['P', 'S']] # Print the result print(result) 

Sortida:

 P S A 28.0 41.0 B 17.0 NaN C14.0 34.0 D 42.0 25.0 ENaN 18.0