How to Get Cell Value from Pandas DataFrame?
Last Updated :
05 Aug, 2022
In this article, we will discuss how to get the cell value from the Pandas Dataframe in Python.
Method 1 : Get a value from a cell of a Dataframe using loc() function
Pandas DataFrame.loc attribute access a group of rows and columns by label(s) or a boolean array in the given DataFrame. Here, we will use loc() function to get cell value.
Python3
import pandas as pd
data = pd.DataFrame({
"id" : [ 7058 , 7059 , 7072 , 7054 ],
"name" : [ 'sravan' , 'jyothika' , 'harsha' , 'ramya' ],
"subjects" : [ 'java' , 'python' , 'html/php' , 'php/js' ]})
print (data[ 'id' ].loc[data.index[ 0 ]])
print (data[ 'name' ].loc[data.index[ 1 ]])
print (data[ 'subjects' ].loc[data.index[ 3 ]])
|
Output:
7058
jyothika
php/js
Method 2: Get a value from a cell of a Dataframe using iloc[]
Dataframe.iloc[] method is used when the index label of a data frame is something other than numeric series of 0, 1, 2, 3….n or in case the user doesn’t know the index label. Here we will use index number to access index value.
Python3
import pandas as pd
print (data[ 'id' ].iloc[ 0 ])
print (data[ 'name' ].iloc[ 0 ])
print (data[ 'subjects' ].iloc[ 0 ])
|
Output:
7058
sravan
java
Method 3: Get a value from a cell of a Dataframe using values() function
values() is an inbuilt method in Python programming language that returns a view object. The view object contains the values of the dictionary, as a list.
Python3
import pandas as pd
print (data[ 'name' ].values[ 0 ])
print (data[ 'id' ].values[ 1 ])
print (data[ 'subjects' ].values[ 3 ])
|
Output:
sravan
7059
php/js
Method 4: Get a value from a cell of a Dataframe using at[] function
To return data in a dataframe at the passed position, use the Pandas at[] function. [position, Column Name] is the format of the passed location. This method functions similarly to Pandas loc[], except at[] returns a single value and so executes more quickly.
Python3
import pandas as pd
print (data.at[ 1 , 'id' ])
print (data.at[ 3 , 'name' ])
print (data.at[ 0 , 'subjects' ])
|
Output:
7059
ramya
java
Method 5: Get a value from a cell of a Dataframe using iat[] function
This function takes a row and column indexes to display cell values in the Dataframe. This is also work same as at[].
Python3
import pandas as pd
data = pd.DataFrame({
"id" : [ 7058 , 7059 , 7072 , 7054 ],
"name" : [ 'sravan' , 'jyothika' , 'harsha' , 'ramya' ],
"subjects" : [ 'java' , 'python' , 'html/php' , 'php/js' ]
}
)
print (data.iat[ 0 , 0 ])
print (data.iat[ 0 , 1 ])
print (data.iat[ 1 , 0 ])
|
Output:
7058
sravan
7059
Share your thoughts in the comments
Please Login to comment...