1

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:

      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. Any ideas?

ekad
  • 14,436
  • 26
  • 44
  • 46
Eduardo
  • 687
  • 1
  • 6
  • 24

1 Answers1

4

The cleanest way is to convert the Name and Zone columns to the category type, specifying the categories and order.

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:

enter image description here

Other options can be found here

Community
  • 1
  • 1
shawnheide
  • 797
  • 4
  • 11