""" Sort a DataFrame in order of decreasing length of name. Break ties by sortting in alphabetical order. """ import sys import pandas as pd url = "http://oit2.scps.nyu.edu/~meretzkm/pandas/dataframe/yob2018.txt" names = ["name", "sex", "births"] df = pd.read_csv(url, names = names) print(df) print() df["length"] = df["name"].str.len() #Add a column giving length of each name. print(df) print() df.sort_values(by = ["length", "name"], ascending = [False, True], inplace = True) print(df) print() del df["length"] #Delete the new column. df.reset_index(drop = True, inplace = True) #Change the index to 0, 1, 2, ... print() with pd.option_context("display.min_rows", 60): print(df) sys.exit(0)
name sex births 0 Emma F 18688 1 Olivia F 17921 2 Ava F 14924 3 Isabella F 14464 4 Sophia F 13928 ... ... .. ... 32028 Zylas M 5 32029 Zyran M 5 32030 Zyrie M 5 32031 Zyron M 5 32032 Zzyzx M 5 [32033 rows x 3 columns] name sex births length 0 Emma F 18688 4 1 Olivia F 17921 6 2 Ava F 14924 3 3 Isabella F 14464 8 4 Sophia F 13928 6 ... ... .. ... ... 32028 Zylas M 5 5 32029 Zyran M 5 5 32030 Zyrie M 5 5 32031 Zyron M 5 5 32032 Zzyzx M 5 5 [32033 rows x 4 columns] name sex births length 31441 Muhammadibrahim M 5 15 31442 Muhammadmustafa M 5 15 30197 Alexanderjames M 5 14 16272 Elizabethgrace F 5 14 12005 Mariaguadalupe F 8 14 ... ... .. ... ... 22358 Yi M 24 2 25575 Yu M 11 2 5103 Zo F 26 2 30097 Zo M 6 2 30102 Zy M 6 2 [32033 rows x 4 columns] name sex births 0 Muhammadibrahim M 5 1 Muhammadmustafa M 5 2 Alexanderjames M 5 3 Elizabethgrace F 5 4 Mariaguadalupe F 8 5 Michaelanthony M 6 6 Oluwafifehanmi F 5 7 Oluwatimilehin M 10 8 Charlotterose F 5 9 Chrysanthemum F 6 10 Elizabethrose F 9 11 Ifeanyichukwu M 7 12 Isabellamarie F 5 13 Josephanthony M 5 14 Kamsiyochukwu F 13 15 Kamsiyochukwu M 12 16 Mariafernanda F 28 17 Mariavictoria F 8 18 Marycatherine F 8 19 Maryelizabeth F 15 20 Marykatherine F 10 21 Michaelangelo M 22 22 Moyosoreoluwa F 5 23 Muhammadyusuf M 9 24 Oluwadamilare M 10 25 Oluwadamilola F 11 26 Oluwadamilola M 5 27 Oluwadarasimi F 41 28 Oluwadarasimi M 17 29 Oluwademilade F 8 ... ... .. ... 32003 Lj M 7 32004 Lo F 5 32005 Lu F 5 32006 Ma F 7 32007 Md M 29 32008 Mi F 11 32009 Mj F 5 32010 Mj M 17 32011 My F 6 32012 Om M 78 32013 Oz M 39 32014 Qi M 5 32015 Ra M 16 32016 Rj M 30 32017 Ry M 10 32018 Sa F 6 32019 Sy M 11 32020 Tj M 30 32021 Tu F 5 32022 Ty F 9 32023 Ty M 466 32024 Vi F 12 32025 Vu M 6 32026 Vy F 25 32027 Xi F 5 32028 Yi M 24 32029 Yu M 11 32030 Zo F 26 32031 Zo M 6 32032 Zy M 6