Dictionaries and conditional selection




In this post, we will learn how to create data using dictionaries. Then we will learn how to access the data using conditional statements.

Dictionaries:

Creating a data table using dictionaries concept in python.

Syntax:    

>> data= pd.DataFrame({"column1":[value11, value12, value13, value14, value15,...],

                                        "column2":[value21, value22, value23, value24, value25,...],

                                        "column3":[value31, value32, value33, value34, value35,...]},

                                            index=[ I1,I2, I3, I4, I5])

>>data

Ex: Create a student details list using dictionaries in python.

>>import numpy as np
>>import pandas as pd
>>df=pd.DataFrame({"Student_name":["Hari","priya","Ravi","Preeti","Fatima","Kiran"],
                                                         "Roll_No": [512,507,568,615,621,521],
                                                         "Age":[ 17, 16,18,19,20,18],
                                                         "height":[64, 64.5,70,65,69,66]},
                                                            index=[0,1,2,3,4,5])
>>df

Output:

  


 


Sorting:
a) sorting a column of a dataframe
Syntax:
 dataframevariable.sort_values('column name',ascending=True)

By default ascending is considered True for ascending order and for descending order provide ascending=False.
b) sorting the output
Syntax:
sorted(condition)

Ex: Arrange the Student names according to their height in ascending order.
>>df.sort_values('height')
Output:


Ex: Arrange the Student names according to their height in descending order.
>>df.sort_values('height',ascending=False)
Output:

Ex: 

Delete a column permanently
Syntax:
del dataframe['column_name']

Ex: Delete the Age column from the Student details.
>> del df['Age']
>>df
Output:

Conditional Selection :
df['condition']['Required column']

Ex: Find Student Roll No whose age is less than 18.
Steps:
step1: Get the rows that satisfies the condition i.e., Age<18
>> df['Age']<18
The output gives boolean values such as True for the row that satisifies the condition and False for the rows that does not satisfies the condition.
Output:
0     True
1     True
2    False
3    False
4    False
5    False
Name: Age, dtype: bool
step2: Get the corresponding the rows with column values
df[df['Age']<18]
Output:


step3: Now get only the Roll No  column that satisfies the condition
>>df[df['Age']<18]['Roll_No']
Output:
0    512
1    507
Name: Roll_No, dtype: int64

Ex: Find Student Roll No whose height is less than 65.
>>df[df['height']<65]['Roll_No']
Output:
0    512
1    507
Name: Roll_No, dtype: int64

Ex: Find Student details whose age is less than 18 and height is greater than 65.

>>df[(df['Age']<18)&(df['height']<65)]
Output:



Happy learning...😊

Comments