Home > Net >  Pandas: Get cell value by row index and column name
Pandas: Get cell value by row index and column name

Time:02-01

Let's say we have a pandas dataframe:

   name  age  sal
0  Alex   20  100
1  Jane   15  200
2  John   25  300
3   Lsd   23  392
4   Mari  21  380

Let's say, a few rows are now deleted and we don't know the indexes that have been deleted. For example, we delete row index 1 using df.drop([1]). And now the data frame comes down to this:

  fname  age  sal
0  Alex   20  100
2  John   25  300
3   Lsd   23  392
4   Mari  21  380

I would like to get the value from row index 3 and column "age". It should return 23. How do I do that?

df.iloc[3, df.columns.get_loc('age')] does not work because it will return 21. I guess iloc takes the consecutive row index?

CodePudding user response:

Use .loc to get rows by label and .iloc to get rows by position:

>>> df.loc[3, 'age']
23

>>> df.iloc[2, df.columns.get_loc('age')]
23

More about Indexing and selecting data

CodePudding user response:

dataset = ({'name':['Alex', 'Jane', 'John', 'Lsd', 'Mari'],
       'age': [20, 15, 25, 23, 21],
       'sal': [100, 200, 300, 392, 380]})
df = pd.DataFrame(dataset)
df.drop([1], inplace=True)
df.loc[3,['age']]
  •  Tags:  
  • Related