Python Forum
How can I sort my column so that NaN is at the bottom?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How can I sort my column so that NaN is at the bottom?
#1
I tried sort_values to put na as last position. But it is not working. I do not wish to remove the NaN fields as it will affect my data analysis later.

I need to sort smokers by population before mortality rate without Nan.

def mortality_rate(row):
    if row['Population 2020 (in thousands)'] >= 50000:
        return row['Total Deaths'] / row['Total Infected']
   
df1['Mortality Rate'] = df1.apply(lambda row: mortality_rate(row), axis = 1)

df1 = df1.sort_values(['Smokers in Population (%)'],ascending=[False])

df1.sort_values(by = ['Mortality Rate'] , axis=0, ascending=False, inplace=False, kind='quicksort', na_position='last')

print(df1[['Country','Smokers in Population (%)', 'Mortality Rate']].head(10))
Current output
>                   Country  Smokers in Population (%)  Mortality Rate
>60              Montenegro                       45.9             NaN
>34                  Greece                       43.4             NaN
>39               Indonesia                       39.4        0.066014
>78                  Serbia                       38.9             NaN
>11  Bosnia and Herzegovina                       38.9             NaN
Desired output
>        Country  Smokers in Population (%)  Mortality Rate
>39    Indonesia                       39.4        0.066014
>30       France                       32.7        0.154892
>32      Germany                       30.6        0.045456
>89       Turkey                       27.2        0.027695
>17        China                       25.6        0.055173
Reply


Messages In This Thread
How can I sort my column so that NaN is at the bottom? - by soft - Feb-05-2021, 01:53 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  how to sort a list without .sort() function letmecode 3 3,483 Dec-28-2020, 11:21 PM
Last Post: perfringo
  [split] Manual Sort without Sort function fulir16 2 3,211 Jun-02-2019, 06:13 AM
Last Post: perfringo
  Manual Sort without Sort function dtweaponx 26 49,219 Jun-01-2019, 06:02 PM
Last Post: SheeppOSU

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020