Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
731 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 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...