Boosted_d16
Boosted_d16

Reputation: 14112

Pandas Python: sort dataframe but don't include given row

I have df which looks like this:

Label                      Base
Label                          
Très à gauche              4.51
Très à droite             10.49
Ni à gauche, ni à droite  24.21
Je ne sais pas             5.60
Au centre                  8.69
A gauche                  23.74
A droite                  22.75

I would like to sort this in acsending order but I dont want "A gauche" and "A droite" included in the sorting.

The code below does what I want but I'm not sure how to exclude "A gauche" and "A droite" from the sorting.

 df_table = df_table.sort(columns="Base",ascending=True)

expected output

Label                      Base
Label                          
Très à gauche              4.51
Je ne sais pas             5.60
Au centre                  8.69
Très à droite             10.49
Ni à gauche, ni à droite  24.21
A gauche                  23.74
A droite                  22.75

Thanks

Upvotes: 2

Views: 4203

Answers (1)

trvrm
trvrm

Reputation: 814

You probably want to filter out the rows you don't want included in your sort operation:

d = df_table
condition = (d.Label=='A gauche') | (d.Label=='A droite')
excluded = d[condition]
included = d[~condition]

Which can then be sorted

sorted = included.sort(columns="Base",ascending=True)

And if you want the excluded rows appended to the end of your data frame, you could do this:

pandas.concat([sorted,excluded])

Upvotes: 5

Related Questions