Issue
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
you can use reindex
to rearrange the rows.
>>> df_A[df_A.index.str[1:].isin(['1','2','5'])].reindex(['s2','s5','s1'])
Student_height Student_weight
s2 158.4 90.2
s5 161.4 78.9
s1 176.2 85.1
Based on data it feels like you want to sort the data on a column after slicing. You can do sorting using sort_values
method.
>>> df_A[df_A.index.str[1:].isin(['1','2','5'])].sort_values("Student_height")
Student_height Student_weight
s2 158.4 90.2
s5 161.4 78.9
s1 176.2 85.1
Answered By - LMKR
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.