'Ordered set of Dataframe values in Pandas

Question:

a series named heights_A with values 176.2, 158.4, 167.6, 156.2, and 161.4. These values represent heights of 5 students of class A.

Label each student as s1, s2, s3, s4, and s5.

another series named weights_A with values 85.1, 90.2, 76.8, 80.4, and 78.9. These values represent weights of 5 students of class A.

Label each student as s1, s2, s3, s4, and s5.

a dataframe named df_A, which holds the height and weight of five students s1, s2, s3, s4 and s5.

Label the columns as Student_height and Student_weight, respectively.

Select the rows corresponding to students s1, s2 and s5 of df_A in the order s2, s5, s1, and capture them in another dataframe df_s2s5s1.

Print the dataframe df_s2s5s1

Wrote to this point on this:

import pandas as pd

import numpy as np  

heights_A =  pd.Series([176.2, 158.4, 167.6, 156.2, 161.4])
heights_A.index = ['s1', 's2', 's3', 's4','s5']

weights_A = pd.Series([85.1, 90.2, 76.8, 80.4 , 78.9])
weights_A.index = ['s1', 's2', 's3', 's4','s5']

df_A = pd.DataFrame()
df_A['Student_height'] = heights_A
df_A['Student_weight'] = weights_A
df_s2s5s1 = df_A.loc[(df_A.index.str.endswith('2') | df_A.index.str.endswith('5') | df_A.index.str.endswith('1') ]

print(df_s2s5s1)

But this is not in order of 2,5,1. Could you help on how to get these in order as such.



Solution 1:[1]

Another version:

df_s2s5s1 = pd.concat([df_A.loc[df_A.index.str.endswith(str(i))] for i in (2, 5, 1)])

Solution 2:[2]

Alternate approach:

df_s2s5s1 = df_A.loc[['s2','s5','s1']]
print(df_s2s5s1)

    Student_height  Student_weight
s2           158.4            90.2
s5           161.4            78.9
s1           176.2            85.1

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Timus
Solution 2 Aleena Aloysius