Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
805 views
in Technique[技术] by (71.8m points)

sorting - 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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])

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...