• Post author:
  • Post category:Pandas
  • Post last modified:October 4, 2024
  • Reading time:14 mins read
You are currently viewing Pandas – How to Get Cell Value From DataFrame?

You can use DataFrame properties loc[], iloc[], at[], iat[] and other ways to get/select a cell value from a Pandas DataFrame. Pandas DataFrame is structured as rows & columns like a table, and a cell is referred to as a basic block that stores the data. Each cell contains information relating to the combination of the row and column.

Advertisements

loc[] & iloc[] are also used to select rows from pandas DataFrame and select columns from pandas DataFrame.

Key Points –

  • Use .loc[] to get a cell value by row label and column label.
  • Use .iloc[] to get a cell value by row and column index.
  • at[] is a faster alternative for accessing a single cell using label-based indexing.
  • .iat[] is similar to .at[], but uses integer-based indexing for faster access to a single cell.
  • Convert the DataFrame to a NumPy array and access elements by array indexing.
  • Prefer .at[] when performance is critical and only one value needs to be accessed.

1. Quick Examples of Get Cell Value of DataFrame

If you are in a hurry, below are some quick examples of how to select cell values from Pandas DataFrame.


# Quick examples of get cell value of DataFrame

# Using loc[]. Get cell value by name & index
print(df.loc['r4']['Duration'])
print(df.loc['r4'][2])

# Using iloc[]. Get cell value by index & name
print(df.iloc[3]['Duration'])
print(df.iloc[3,2])

# Using DataFrame.at[]
print(df.at['r4','Duration'])
print(df.at[df.index[3],'Duration'])

# Using DataFrame.iat[]
print(df.iat[3,2])

# Get a cell value
print(df["Duration"].values[3])

# Get cell value from last row
print(df.iloc[-1,2])
print(df.iloc[-1]['Duration'])
print(df.at[df.index[-1],'Duration'])

Now, let’s create a DataFrame with a few rows and columns and execute some examples, and validate the results. Our DataFrame contains column names Courses, Fee, Duration, Discount.


# Create DataFrame
import pandas as pd
technologies = {
     'Courses':["Spark","PySpark","Hadoop","Python","pandas"],
     'Fee' :[24000,25000,25000,24000,24000],
     'Duration':['30day','50days','55days', '40days','60days'],
     'Discount':[1000,2300,1000,1200,2500]
          }
index_labels=['r1','r2','r3','r4','r5']
df = pd.DataFrame(technologies, index=index_labels)
print("Create DataFrame:\n", df)

Yields below output.

Pandas DataFrame Get Value Cell

2. Using DataFrame.loc[] to Get a Cell Value by Column Name

In Pandas, DataFrame.loc[] property is used to get a specific cell value by row & label name(column name). Below all examples return a cell value from the row label r4 and Duration column (3rd column).


# Using loc[]. Get cell value by name & index
print(df.loc['r4']['Duration'])
print(df.loc['r4','Duration'])
print(df.loc['r4'][2])

Yields below output. From the above examples df.loc['r4'] returns a pandas Series.


# Output:
40days

3. Using DataFrame.iloc[] to Get a Cell Value by Column Position

If you want to get a cell value by column number or index position use DataFrame.iloc[], index position starts from 0 to length-1 (index starts from zero). In order to refer last column use -1 as the column position.


# Using iloc[]. Get cell value by index & name
print(df.iloc[3]['Duration'])
print(df.iloc[3][2])
print(df.iloc[3,2])

This returns the same output as above. Note that iloc[] property doesn’t support df.iloc[3,'Duration'], by using this notation, returns an error.

4. Using DataFrame.at[] to select Specific Cell Value by Column Label Name

DataFrame.at[] property is used to access a single cell by row and column label pair. Like loc[] this doesn’t support column by position. This performs better when you want to get a specific cell value from Pandas DataFrame as it uses both row and column labels. Note that at[] property doesn’t support a negative index to refer rows or columns from last.


# Using DataFrame.at[]
print(df.at['r4','Duration'])
print(df.at[df.index[3],'Duration'])

These examples also yield the same output 40days.

5. Using DataFrame.iat[] select Specific Cell Value by Column Position

DataFrame.iat[] is another property to select a specific cell value by row and column position. Using this you can refer to columns only by position but not by a label. This also doesn’t support a negative index or column position.


# Using DataFrame.iat[]
print(df.iat[3,2])

6. Select Cell Value from DataFrame Using df[‘col_name’].values[]

We can use df['col_name'].values[] to get 1×1 DataFrame as a NumPy array, then access the first and only value of that array to get a cell value, for instance, df["Duration"].values[3].


# Get a cell value
print(df["Duration"].values[3])

7. Get Cell Value from Last Row of Pandas DataFrame

If you want to get a specific cell value from the last Row of Pandas DataFrame, use the negative index to point to the rows from the last. For example, Index -1 represents the last row, and -2 for the second row from the last. Similarly, you should also use -1 for the last column.


# Get cell value from last row
print(df.iloc[-1,2])                  # prints 60days
print(df.iloc[-1]['Duration'])        # prints 60days
print(df.at[df.index[-1],'Duration']) # prints 60days

To select the cell value of the last row and last column use df.iloc[-1,-1], this returns 2500. Similarly, you can also try other approaches.

Frequently Asked Questions of Get Cell Value

How do I get the value of a specific cell in a Pandas DataFrame?

You can use the .at or .iat accessor to get the value of a specific cell in a DataFrame. The .at accessor uses row and column labels, while the .iat accessor uses integer-based indices.

How do I get the first (or last) cell value in a Pandas DataFrame?

To get the first cell value in a DataFrame, you can use the .iloc[]attribute of Pandas with index 0 for both the row and column. For the last cell value, you can use -1 as the row index.

How do I get cell values from a Pandas Series (a single column)?

If you have a Pandas Series, you can access cell values using integer-based indexing. For example, value = series.iloc[index]

How can I get the cell values in a specific row or column as a list or array?

To get the cell values in a specific row as a list, you can use .loc[] or .iloc[] along with the .tolist() method. For columns, you can directly access the column and convert it to a list using .tolist()

Conclusion

In this article, you have learned how to get or select a specific cell value from pandas DataFrame using the .iloc[], .loc[], .iat[] & .at[] properties. Also, you have learned how to get a specific value from the last row and last column with examples.

Happy Learning !!

References

Leave a Reply

This Post Has One Comment

  1. NNK

    Thanks Larsen for pointing it out. You are right and I have corrected it.