Skip to content
Advertisement

How to sort a dataframe with strings

I got an code running that imports an excel file, and i want to be able to sort some of the data in it and write it to a new excel file. I got the code working somewhat as I want, but can’t make it sort the values as wanted… I want to sort the df from the column named “Varetekst”(Sorry for not written in english!) How can I sort the df from a column containing strings? I have tried multiple solutions and I think maybe the problem is that the column are a obj and not a str.

 filt_liste_fisk_1 = (liste_fisk[liste_fisk['EAN'].str.len() <= 4])
    filt_liste_fisk = liste_fisk[liste_fisk['EAN'].str.startswith("2000")]
    fiskeliste = pd.read_excel(r'C:UsersKevinDesktopMENYFiltrerings listerliste_fisk.xlsx',index_col = False)
    fiskeliste['EAN'] = fiskeliste['EAN'].map(str)
    fiskeliste1 = df[df['EAN'].isin(set(fiskeliste['EAN']))]
    fiskliste = pd.concat([filt_liste_fisk_1, filt_liste_fisk,fiskeliste1])
    print_fisk = fiskliste.drop(['Lagertype'], axis = 1).drop(['Vindu'], axis = 1)
    print_fisk.astype(({'Varetekst': 'str'}))
    print_fisk.sort_values(by=["Varetekst"], ascending=True)  
    print(print_fisk)

There is more to the code, where I import it and write it to an excel file. But this is where I do all the work, so this is what the code output:

   Bestilt Enhet                                          Varetekst       EAN
107       1    KG  Ferske Reker   | (Minimum holdbarhetsdato: 31-...      1893
108     0.7    KG  Ferske Reker   | (Minimum holdbarhetsdato: 31-...      1893
120     0.6    KG  Ferske Reker   | (Minimum holdbarhetsdato: 31-...      1893
123     1.6    KG  Ferske Reker   | (Minimum holdbarhetsdato: 31-...      1893
99        1   STK  Krabbeskjell Håndrenset m/Klokjøtt pr stykk  |...  20001951
104     0.6    KG  Skrei skiver pr Kg  | (Minimum holdbarhetsdato...  20001922
106       1   STK  Blåskjell Levende pr Kg  | (Minimum holdbarhet...  20001990
113     0.5    KG  Rå Skreirogn   | (Minimum holdbarhetsdato: 01-...  20001941
117     0.6    KG  Skrei skiver pr Kg  | (Minimum holdbarhetsdato...  20001922
119       1   STK  Blåskjell Levende pr Kg  | (Minimum holdbarhet...  20001990
122     0.3    KG  Steinbit Filet pr Kg  | (Minimum holdbarhetsda...  20001927
133     0.5    KG                          Reker 60/80 Frosne pr Kg   20005200
Filtrering ferdig!

Advertisement

Answer

Sorting does not get saved in place by default (as with pandas operations in general).

Either set inplace=True:

print_fisk.sort_values(by=["Varetekst"], ascending=True, inplace=True)

Or assign back to print_fisk if inplace is not set:

print_fisk = print_fisk.sort_values(by=["Varetekst"], ascending=True)
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement