Home > Enterprise >  how to extract specific key and value from a dataframe python
how to extract specific key and value from a dataframe python

Time:07-02

[enter image description here][1][

I want to extract name(a) and respective scores(90) from a data frame As you can see here I used iloc method to get the scores of respective names. The only problem is if names get interchanged in a dataframe we can't get accurate scores. Can we extract name as key and score as a value using python? By this way we can avoid hardcoding.

Code :

name_dict = {
    'Name': ['a','b','c','d'],
    'Score': [90,80,95,20]}
df = pd.DataFrame(name_dict)

print (df)

df.iloc[0,1]

Output :

90

CodePudding user response:

Set the index of the dataframe to the Name column

df.set_index('Name', inplace=True)

Then you can fetch the score as

df.loc['a', 'Score']
  • Related