Pandas: Get cell value by row index and column name

Question:

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?

Asked By: Sedmaister

||

Answers:

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

Answered By: Corralien
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']]
Answered By: ARamirez

try this one:
[label, column name]

value = df.loc[1,"column_name"]
Answered By: Carlost

Another way apart from the accepted answere is df.at[3, "age"]

Answered By: Mainland
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.