简体   繁体   English

仅对 pandas dataframe 中的特定行子集进行排序

[英]Sorting only specific subset of rows in pandas dataframe

I spent some time trying to figure out a solution to but haven't been able to figure a simple and clean solution to my problem.我花了一些时间试图找出一个解决方案,但未能找到一个简单干净的解决方案来解决我的问题。 Basically I have the following dataframe:基本上我有以下 dataframe:

Plane Parts平面零件 Quantity数量 is_plane is_plane
G6_32 FAB G6_32工厂 1 1个 True真的
G6_32 KIT G6_32套件 2 2个 True真的
Item D D项 2 2个 False错误的
Item C项目 C 4 4个 False错误的
Item A项目A 5 5个 False错误的
G6_32 SITE G6_32 站点 5 5个 True真的
G6_32 SPACE G6_32 空间 6 6个 True真的
Item C项目 C 2 2个 False错误的
Item A项目A 1 1个 False错误的
Item F F项 2 2个 False错误的

I need to sort only the subset of rows which have is_plane == False .我只需要对具有is_plane == False的行子集进行排序。 So at the end my final result would look like:所以最后我的最终结果是这样的:

Plane Parts平面零件 Quantity数量 is_plane is_plane
G6_32 FAB G6_32工厂 1 1个 True真的
G6_32 KIT G6_32套件 2 2个 True真的
Item A项目A 5 5个 False错误的
Item C项目 C 4 4个 False错误的
Item D D项 2 2个 False错误的
G6_32 SITE G6_32 站点 5 5个 True真的
G6_32 SPACE G6_32 空间 6 6个 True真的
Item A项目A 1 1个 False错误的
Item C项目 C 2 2个 False错误的
Item F F项 2 2个 False错误的

Notice that the rows which is_plane == True are not supposed to be sorted and kept the original position. Any idea on how to achieve it?请注意, is_plane == True的行不应排序并保留原始 position。关于如何实现它的任何想法?

make grouper for grouping为分组制作石斑鱼

grouper = df['is_plane'].ne(df['is_plane'].shift(1)).cumsum()

grouper : grouper

0    1
1    1
2    2
3    2
4    2
5    3
6    3
7    4
8    4
9    4
Name: is_plane, dtype: int32

use groupby by grouper按石斑鱼分组

group that its 'Plane Parts' is all False, sort_values by Plane Parts.将其“Plane Parts”全部为 False,按 Plane Parts 排序值。

df.groupby(grouper).apply(lambda x: x.sort_values('Plane Parts') if x['is_plane'].sum() == 0 else x).droplevel(0)

output: output:

    Plane Parts Quantity    is_plane
0   G6_32 FAB   1           True
1   G6_32 KIT   2           True
4   Item A      5           False
3   Item C      4           False
2   Item D      2           False
5   G6_32 SITE  5           True
6   G6_32 SPACE 6           True
8   Item A      1           False
7   Item C      2           False
9   Item F      2           False

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM