Get the specified row value of a given Pandas DataFrame

Get the specified row value of a given Pandas DataFrame

To retrieve a specific row's value from a Pandas DataFrame, you can use the .iloc[] or .loc[] method.

  1. Using .iloc[] for integer-location based indexing:

    If you want to retrieve a row by its integer index (0-based), you can use .iloc[].

    import pandas as pd # Sample DataFrame df = pd.DataFrame({ 'A': [1, 2, 3], 'B': [4, 5, 6], 'C': [7, 8, 9] }) # Get the values of the 2nd row (0-based index) row_values = df.iloc[1].values print(row_values) # Output: [2 5 8] 
  2. Using .loc[] for label-based indexing:

    If your DataFrame has a custom index and you want to retrieve a row by its label, you can use .loc[].

    df = pd.DataFrame({ 'A': [1, 2, 3], 'B': [4, 5, 6], 'C': [7, 8, 9] }, index=['x', 'y', 'z']) # Get the values of the row with the label 'y' row_values = df.loc['y'].values print(row_values) # Output: [2 5 8] 
  3. Getting the row as a Series:

    If you'd like to retrieve the row as a Pandas Series, you can simply omit .values.

    row_series = df.iloc[1] print(row_series) 

    The output will be:

    A 2 B 5 C 8 Name: 1, dtype: int64 

Keep in mind, if you're looking to retrieve multiple rows, you can pass a list of indices or labels to .iloc[] or .loc[], respectively.


More Tags

spline spring-boot-actuator background-image firebase-mlkit asp.net-mvc-scaffolding searching data-url dotnet-cli crontrigger asp.net-core-webapi

More Programming Guides

Other Guides

More Programming Examples