'How to print specific data based on its rank in data frame

I have data of cooking oil and its boiling temp and ranked it by highest boiling temp

print(df_ranked)

    ranking               oil  boil_temp
0         1           avocado        270
1         2         sunflower        252
2         3       beef_tallow        250
3         3  butter_clarified        250
4         3           mustard        250
5         4              palm        235
6         5              corn        230
7         6         grapeseed        216
8         7            canola        204
9         8           coconut        200
10        9          olive_ev        160
11       10            butter        150

I used print function to print data with certain rank and this is the result

print(df_ranked.loc[df_ranked['ranking'].isin([3])])

 ranking               oil  boil_temp
2        3       beef_tallow        250
3        3  butter_clarified        250
4        3           mustard        250

I want the result to be more simple like this

beef_tallow, 250
butter_clarified, 250
mustard, 250

or this

Oil with third highest boiling temperature: beef_tallow, butter_clarified, mustard

I tried using loop to get result like that, but the code I used seems to be wrong because it didn't print anything

for i in df_ranked['ranking'].items():
  for x in df_ranked['oil'].items():
    if (i==3):
       print(f'Oil with third highest boiling temperature:{x}')


Solution 1:[1]

You could use:

s = (df_ranked.loc[df_ranked['ranking'].isin([3]), ['oil', 'boil_temp']]
              .astype(str).agg(', '.join, axis=1)
     )
# 2         beef_tallow, 250
# 3    butter_clarified, 250
# 4             mustard, 250
# dtype: object

print('\n'.join(s))

output:

beef_tallow, 250
butter_clarified, 250
mustard, 250

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 mozway