[英]Sort data within group - Pandas Dataframe
I have the following data frame: 我有以下数据框:
As Comb Mu(+) Name Zone f´c
33 0.37 2 6.408225 Beam_13 Final 30.0
29 0.37 2 6.408225 Beam_13 Begin 30.0
31 0.94 2 16.408225 Beam_13 Middle 30.0
15 0.54 2 9.504839 Beam_7 Final 30.0
11 0.54 2 9.504839 Beam_7 Begin 30.0
13 1.12 2 19.504839 Beam_7 Middle 30.0
I need to sort the data by Name
and then by Zone
within a group as shown in the expected output below: 我需要按
Name
排序数据,然后按组内的Zone
排序,如下面的预期输出所示:
As Comb Mu(+) Name Zone f´c
11 0.54 2 9.504839 Beam_7 Begin 30.0
13 1.12 2 19.504839 Beam_7 Middle 30.0
15 0.54 2 9.504839 Beam_7 Final 30.0
29 0.37 2 6.408225 Beam_13 Begin 30.0
31 0.94 2 16.408225 Beam_13 Middle 30.0
33 0.37 2 6.408225 Beam_13 Final 30.0
I can order by index, but not by name and zone within the Name
group. 我可以按索引排序,但不能按
Name
组中的名称和区域排序。 Any ideas? 有任何想法吗?
The cleanest way is to convert the Name
and Zone
columns to the category type, specifying the categories and order. 最干净的方法是将
Name
和Zone
列转换为类别类型,指定类别和顺序。
from io import StringIO
data = """
As,Comb,Mu(+),Name,Zone,f´c
33,0.37,2,6.408225,Beam_13,Final,30.0
29,0.37,2,6.408225,Beam_13,Begin,30.0
31,0.94,2,16.408225,Beam_13,Middle,30.0
15,0.54,2,9.504839,Beam_7,Final,30.0
11,0.54,2,9.504839,Beam_7,Begin,30.0
13,1.12,2,19.504839,Beam_7,Middle,30.0
"""
df = pd.read_csv(StringIO(data))
# convert Name and Zone to ordinal/category type
df.Name = df.Name.astype('category', categories=["Beam_7", "Beam_13"], ordered=True)
df.Zone = df.Zone.astype('category', categories=["Begin", "Middle", "Final"], ordered=True)
df.sort_values(by=['Name', 'Zone'])
Here's the output: 这是输出:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.