5

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?

Sedmaister
  • 475
  • 1
  • 4
  • 11
  • Then it's better to set your index to 'fname': `df = df.set_index('fname')`. If you're going to referencing rows by that. There's not much point in using an arbitrary integer index when you can use something better. (unless there's a possiblity of duplicates in 'fname') – smci Jan 31 '22 at 18:29
  • 1
    Shouldn't guess but read the docs and use `loc` here :) – Mustafa Aydın Jan 31 '22 at 18:30
  • i think this thread answers your question https://stackoverflow.com/questions/31593201/how-are-iloc-and-loc-different – Tushar Mazumdar Jan 31 '22 at 18:52
  • Related: "[pandas loc vs. iloc vs. at vs. iat?](/q/28757389/90527)" – outis Dec 28 '22 at 21:11

4 Answers4

17

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

Corralien
  • 109,409
  • 8
  • 28
  • 52
0
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']]
ARamirez
  • 1
  • 1
0

try this one: [label, column name]

value = df.loc[1,"column_name"]
xxx
  • 1,153
  • 1
  • 11
  • 23
Carlost
  • 478
  • 5
  • 13
0

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

Mainland
  • 4,110
  • 3
  • 25
  • 56