Home > Enterprise >  In Python Pandas DataFrames with column of unique row IDs, how to find column value given row ID?
In Python Pandas DataFrames with column of unique row IDs, how to find column value given row ID?

Time:01-20

I'm fairly new to Pandas and DataFrames. I have hacked out a solution to my issue, but it is convoluted, so I think I might have done it "wrong".

Let be given a DataFrame with a column that has a unique ID for each row, like so:

df1 = pd.DataFrame(data={'id': ['ID1','ID2','ID3'], 'col': ['a','b','a']}) 

How do I look up the col value of the row with ID1, using the id value, not the index?

I know I can do df1.loc[df1.id == 'ID1'].col.item() to obtain the same as using the index df1.col.iloc[0], but it just seems convoluted.

Is it the right approach or does there exist a simpler / more recommended way of obtaining the same result?

CodePudding user response:

I think your solution is perfectly fine. However, since the id values are unique, you may want to consider making them the index themselves. Then you would have a shorter way to look up the values:

df1.set_index('id', inplace=True)

df1.col['ID1']
'a'
  •  Tags:  
  • Related