Home » Python » python – simply selecting a column in a specific row-Exceptionshub

python – simply selecting a column in a specific row-Exceptionshub

Posted by: admin February 24, 2020 Leave a comment


Ok, my frustration has hit epic proportions. I am new to Pandas and trying to use it on an excel db i have, however, i cannot seem to figure out what should be a VERY simple action.
I have a dataframe as such:

1  123 Bob NY
1  123 Bob PA
2  124 Jim NY
2  124 Jim PA
3  125 Sue NY

all i need is to be able to locate and print the ID of a record by the unique combination of UID and STATE.

The closest I can come up with is this:

temp_db = fd_db.loc[(fd_db['UID'] == "1") & (fd_db['STATE'] == "NY")]

but this still grabs all UID and not ONLY the one with the STATE

Then, when i try to print the result


prints this:

['1', '1']

I need just the data and not the structure.

My end result needs to be just to print to the screen : 1

Any help is much appreciated.

How to&Answers:
fd_db.loc[(fd_db['UID'] == 123) & (fd_db['STATE'] == 'NY')]['ID'].iloc[0]


I think it’s because your UID condition is wrong : the UID column an Integer and you give a String.

For example when I run this :

df.loc[(df['UID'] == "123") & (df['STATE'] == 'NY')]

The output is :

Empty DataFrame
Columns: [ID, UID, NAME, STATE]
Index: []

but when I consider UID as an Integer :

df.loc[(df['UID'] == 123) & (df['STATE'] == 'NY')]

It output :

0   1  123  Bob    NY

I hope that will help you !