Get a Value From a Cell of a Pandas DataFrame

  1. iloc to Get Value From a Cell of a Pandas Dataframe
  2. iat and at to Get Value From a Cell of a Pandas Dataframe
  3. df['col_name'].values[] to Get Value From a Cell of a Pandas Dataframe

We will introduce methods to get the value of a cell in Pandas Dataframe. They include iloc and iat. ['col_name'].values[] is also a solution especially if we don’t want to get the return type as pandas.Series.

iloc to Get Value From a Cell of a Pandas Dataframe

iloc is the most efficient way to get a value from the cell of a Pandas dataframe. Suppose we have a Dataframe with the columns’ names as price and stock, and we want to get a value from the 3rd row to check the price and stock availability.

First, we need to access rows and then the value using the column name.

Example Codes:

# python 3.x
import pandas as pd
df = pd.DataFrame({
    'name':
    ['orange','banana','lemon','mango','apple'],
    'price':
    [2,3,7,21,11],
    'stock':
    ['Yes','No','Yes','No','Yes']
})
print(df.iloc[2]['price'])
print(df.iloc[2]['stock'])

Output:

7
Yes

iloc gets rows (or columns) at particular positions in the index. That’s why it only takes an integer as the argument. And loc gets rows (or columns) with the given labels from the index.

iat and at to Get Value From a Cell of a Pandas Dataframe

iat and at are fast accesses for scalars to get the value from a cell of a Pandas Dataframe.

Example Codes:

# python 3.x
import pandas as pd
df = pd.DataFrame({
    'name':
    ['orange','banana','lemon','mango','apple'],
    'price':
    [2,3,7,21,11],
    'stock':
    ['Yes','No','Yes','No','Yes']
})
print(df.iat[0,0])
print(df.at[1,'stock'])

Output:

orange
No

To get the last row entry, we will use at[df.index[-1],'stock'].

Example Codes:

# python 3.x
import pandas as pd
df = pd.DataFrame({
    'name':
    ['orange','banana','lemon','mango','apple'],
    'price':
    [2,3,7,21,11],
    'stock':
    ['Yes','No','Yes','No','Yes']
})
print(df.at[df.index[-1],'stock'])

Output:

Yes

df['col_name'].values[] to Get Value From a Cell of a Pandas Dataframe

df['col_name'].values[] will first convert datafarme column into 1-D array then access the value at index of that array:

Example Codes:

# python 3.x
import pandas as pd
df = pd.DataFrame({
    'name':
    ['orange','banana','lemon','mango','apple'],
    'price':
    [2,3,7,21,11],
    'stock':
    ['Yes','No','Yes','No','Yes']
})
print(df['stock'].values[0])

Output:

Yes

It does not return a pandas.Series, and it’s the simplest to use.

Contribute
DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page.

Related Article - Pandas DataFrame

  • Subtract Two Columns of a Pandas DataFrame
  • Count the Frequency a Value Occurs in Pandas Dataframe