0

I have a DF where the index is equal strings.

df = pd.DataFrame([[0, 2, 3], [0, 4, 1], [10, 20, 30]],

                  index=['a', 'a', 'a'], columns=['A', 'B', 'C'])
>>> df
    A   B   C
a   0   2   3
a   0   4   1
a  10  20  30

Let's say I am trying to access the value in col 'B' at the first row. I am using something like this:

>>> df.iloc[0]['B']
2

Reading the post here it seems .at is recommended to be used for efficiency. Is there any better way in my example to return the value by the index row number and column name?

armin
  • 591
  • 3
  • 10
  • If you are doing once, it shouldn't be matter. If you are trying to do so repeatedly, remember that it is not recommended to do so :D – Quang Hoang Feb 23 '21 at 03:47
  • Why don't you give `df.iloc[0,1]` Using iloc is much better as you can use the index value – Joe Ferndz Feb 23 '21 at 03:48
  • @QuangHoang Thanks for the response. Unfortunately, I have to do it in a loop. what is your suggestion? – armin Feb 23 '21 at 03:50
  • Unfortunately I don't have any suggestions. My point is that you can try to find a vectorized solution to access all needed elements without a loop. – Quang Hoang Feb 23 '21 at 03:53

1 Answers1

0

Try with iat with get_indexer

df.iat[0,df.columns.get_indexer(['B'])[0]]
Out[124]: 2
BENY
  • 317,841
  • 20
  • 164
  • 234