Accessing the index/row/column from a selected cell in Pandas/Python

13,325

Updated

Use iloc. Example as follows:

df.iloc[row, column] # accepts ints

This will give you access to that column and row.

Updated

So we find the row index and then do my original suggestion and get the entire row.

row = df.loc[df['address_value']==lot_number].index[0]
df.iloc[row]
Share:
13,325
rustyshackleford
Author by

rustyshackleford

Updated on June 05, 2022

Comments

  • rustyshackleford
    rustyshackleford about 2 years

    I'm supposed to be turning an excel spreadsheet with nontrivial functions into a web application. I have decided to work with Pandas, and I'm wondering what the best way to approach this is.

    One of the things I need to do is allow people to input a certain number (we'll call this lot_number) and access other values in the same row.

    For example, if lot_number = 3, address_value in a different column will be 555 Something Street. All of the lot_numbers and address_value entries are different.

    My question is this: how can I access address_value using pandas depending on lot_number?

  • rustyshackleford
    rustyshackleford over 6 years
    I don't think this appropriately addresses the question. The row will need to come from whatever row lot_number is in.
  • Adders
    Adders over 6 years
    Sorry about that - See how you get on with the new updated
  • rustyshackleford
    rustyshackleford over 6 years
    Hi Wen. This looks perfect and works when I run your example, but with the csv I'm importing, I get this error. ValueError: Row labels must have same size as column labels . Any idea why?
  • BENY
    BENY over 6 years
    @vipertherapper you have duplicated in columns ['lot_number']
  • BENY
    BENY over 6 years
    @vipertherapper updated , BTW , you reach 15 reputation , you can upvote , and also accept the answer you like :)
  • Adders
    Adders over 6 years
    Wen has enough rep. Help me out haha
  • rustyshackleford
    rustyshackleford over 6 years
    Yes, I'll accept your answer as soon as I can figure this out. I'm still getting an error though. File "pandas/_libs/index.pyx".... KeyError: 'lot_number'
  • BENY
    BENY over 6 years
    @vipertherapper maybe you have blank like lot_number
  • rustyshackleford
    rustyshackleford over 6 years
    This seems like it may work, but it looks like it's returning too much data. Hang on a sec and let me check it out
  • rustyshackleford
    rustyshackleford over 6 years
    I think this is close. I'm getting this error now. IndexError: index 0 is out of bounds for axis 0 with size 0
  • Adders
    Adders over 6 years
    Same here. Try [row, :]
  • rustyshackleford
    rustyshackleford over 6 years
  • rustyshackleford
    rustyshackleford over 6 years
    I just converted that row/column into a dictionary and had a much easier time working with that. Thanks for the help.