Pandas – How to Get Cell Value From DataFrame?

Spread the love

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.

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

1. Quick Examples of Get Cell Value of DataFrame

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


# Belwo are quick example 
# 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.


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(df)

Yields below output.


    Courses    Fee Duration  Discount
r1    Spark  24000    30day      1000
r2  PySpark  25000   50days      2300
r3   Hadoop  25000   55days      1000
r4   Python  24000   40days      1200
r5   pandas  24000   60days      2500

1. 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.


40days

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

If you wanted 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.

3. 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 wanted to get a specific cell value from Pandas DataFrame as it uses both row and column labels. Note that at[] property doesn’t support 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.

4.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 column only by position but not by a label. This also doesn’t support negative index or column position.


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

5. 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])

6. Get Cell Value from Last Row of Pandas DataFrame

If you wanted to get a specific cell value from the last Row of Pandas DataFrame, use the negative index to point the rows from 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.

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 row, last column with examples.

Happy Learning !!

References

Naveen (NNK)

SparkByExamples.com is a Big Data and Spark examples community page, all examples are simple and easy to understand and well tested in our development environment Read more ..

Leave a Reply

This Post Has One Comment

  1. NNK

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

You are currently viewing Pandas – How to Get Cell Value From DataFrame?