简体   繁体   中英

how to extract specific key and value from a dataframe python

[在此处输入图片描述][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

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']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM