Thursday, 21 September 2023

PlantUML: Working with Object Diagrams

Object diagram is a structural diagram that shows the instances of classifiers in the models.

helloworld.txt

@startuml

	object "ABC Demo Corporaiton" as corp

	object "HR:Department" as hr
	object "Finance:Department" as finance
	object "CampusRecruit:Department" as campusRecruit

	object "Emp1:Employee" as emp1
	object "Emp1:Employee" as emp2
	object "Emp1:Employee" as emp3
	object "Emp1:Employee" as emp4


	corp -- hr
	corp -- finance
	corp -- campusRecruit

	hr -- emp1
	hr -- emp2
	finance -- emp3
	campusRecruit -- emp4

@enduml

Above snippet generate below object diagram.



 

 

Previous                                                 Next                                                 Home

How to Get the Number of Rows in a Pandas DataFrame

You can get the number of rows in a Dataframe using either ‘shape’ attribute or the ‘len()’ function.

 

Example 1: To get the total number of rows using the shape attribute

total_rows = df.shape[0]

 

Example 2: To fet the total number of rows using the len function

total_rows = len(df)

 

Find the below working application.

 

number_of_rows.py

import pandas as pd

# Create a sample DataFrame
data = {'Name': ['Krishna', 'Ram', 'Joel'],
        'Age': [34, 25, 29],
        'City': ['Bangalore', 'Chennai', 'Hyderabad']}

df = pd.DataFrame(data)

# Get the total number of rows using the shape attribute
total_rows = df.shape[0]
print("total_rows : ", total_rows)

# Get the total number of rows using the len function
total_rows = len(df)
print("total_rows : ", total_rows)

Output

total_rows :  3
total_rows :  3




 

 

Previous                                                 Next                                                 Home

How to Get the First N Rows of a Pandas DataFrame

Dataframe head method return first n rows.

 

Example

df.head(2)

 

Above snippet return first two rows of the dataframe.

 

df.head()

If you do not pass any argument to the head() method, it print 5 rows by default.

 

head() method support negative values

For negative values of `n`, this function returns all rows except the last `|n|` rows, equivalent to ``df[:n]``.

 

Example

total_rows = len(df)
total_rows_minus_three = total_rows-3
first_three_rows = df.head(-total_rows_minus_three)

 

‘df.head(-total_rows_minus_three)’ statement return first 3 rows of the dataframe (assume total rows are > 3).

 

Find the below working application.

first_n_rows.py
# Import the pandas Library.
import pandas as pd

# Specify the file path to the CSV file relative to the project directory.
file_path = '../../data/csv/ipl_matches.csv'

# Set options to display all columns and increase the maximum width to print the columns in same row
pd.set_option('display.max_columns', None)
pd.set_option('display.width', 1000)

# Read the CSV file into a DataFrame
df = pd.read_csv(file_path)

first_five_rows = df.head()
print("First five rows\n", first_five_rows)

first_two_rows = df.head(2)
print("\nFirst two rows\n", first_two_rows)

# Get the total number of rows using the len() function
total_rows = len(df)
total_rows_minus_three = total_rows-3
first_three_rows = df.head(-total_rows_minus_three)
print("\nFirst three rows\n", first_three_rows)

 

Output

First five rows
        id        city        date player_of_match                                       venue  neutral_venue                        team1                        team2                  toss_winner toss_decision                       winner   result  result_margin eliminator method    umpire1         umpire2
0  335982   Bangalore  2008-04-18     BB McCullum                       M Chinnaswamy Stadium              0  Royal Challengers Bangalore        Kolkata Knight Riders  Royal Challengers Bangalore         field        Kolkata Knight Riders     runs          140.0          N    NaN  Asad Rauf     RE Koertzen
1  335983  Chandigarh  2008-04-19      MEK Hussey  Punjab Cricket Association Stadium, Mohali              0              Kings XI Punjab          Chennai Super Kings          Chennai Super Kings           bat          Chennai Super Kings     runs           33.0          N    NaN  MR Benson      SL Shastri
2  335984       Delhi  2008-04-19     MF Maharoof                            Feroz Shah Kotla              0             Delhi Daredevils             Rajasthan Royals             Rajasthan Royals           bat             Delhi Daredevils  wickets            9.0          N    NaN  Aleem Dar  GA Pratapkumar
3  335985      Mumbai  2008-04-20      MV Boucher                            Wankhede Stadium              0               Mumbai Indians  Royal Challengers Bangalore               Mumbai Indians           bat  Royal Challengers Bangalore  wickets            5.0          N    NaN   SJ Davis       DJ Harper
4  335986     Kolkata  2008-04-20       DJ Hussey                                Eden Gardens              0        Kolkata Knight Riders              Deccan Chargers              Deccan Chargers           bat        Kolkata Knight Riders  wickets            5.0          N    NaN  BF Bowden     K Hariharan

First two rows
        id        city        date player_of_match                                       venue  neutral_venue                        team1                  team2                  toss_winner toss_decision                 winner result  result_margin eliminator method    umpire1      umpire2
0  335982   Bangalore  2008-04-18     BB McCullum                       M Chinnaswamy Stadium              0  Royal Challengers Bangalore  Kolkata Knight Riders  Royal Challengers Bangalore         field  Kolkata Knight Riders   runs          140.0          N    NaN  Asad Rauf  RE Koertzen
1  335983  Chandigarh  2008-04-19      MEK Hussey  Punjab Cricket Association Stadium, Mohali              0              Kings XI Punjab    Chennai Super Kings          Chennai Super Kings           bat    Chennai Super Kings   runs           33.0          N    NaN  MR Benson   SL Shastri

First three rows
        id        city        date player_of_match                                       venue  neutral_venue                        team1                  team2                  toss_winner toss_decision                 winner   result  result_margin eliminator method    umpire1         umpire2
0  335982   Bangalore  2008-04-18     BB McCullum                       M Chinnaswamy Stadium              0  Royal Challengers Bangalore  Kolkata Knight Riders  Royal Challengers Bangalore         field  Kolkata Knight Riders     runs          140.0          N    NaN  Asad Rauf     RE Koertzen
1  335983  Chandigarh  2008-04-19      MEK Hussey  Punjab Cricket Association Stadium, Mohali              0              Kings XI Punjab    Chennai Super Kings          Chennai Super Kings           bat    Chennai Super Kings     runs           33.0          N    NaN  MR Benson      SL Shastri
2  335984       Delhi  2008-04-19     MF Maharoof                            Feroz Shah Kotla              0             Delhi Daredevils       Rajasthan Royals             Rajasthan Royals           bat       Delhi Daredevils  wickets            9.0          N    NaN  Aleem Dar  GA Pratapkumar

 

 


Previous                                                 Next                                                 Home

Pandas: Dataframes: Hello World application

I am using the dataset from https://www.kaggle.com/datasets/patrickb1912/ipl-complete-dataset-20082020, to demonstrate the hello world application.

 

Project hierarchy looks like below.

data
|____csv
| |____ipl_matches.csv
src
|____csv
| |____hello_world.py

 

As you see above snippet, there are two folders

a.   data : to hold the sample data sets

b.   src : to hold the panda programs.

 

Follow step-by-step procedure helps to understand the hello world program in Pandas.

 

Step 1: Create a file hello_world.py in the project src/csv directory.

 

Step 2: Import the pandas Library.

import pandas as pd

 

Step 3: Specify the file path to the CSV file relative to the project directory.

file_path = '../../data/csv/ipl_matches.csv'

 

Step 4: Set the maximum number of columns to display as unlimited.

pd.set_option('display.max_columns', None)

 

Step 5: Read the CSV file into a DataFrame.

df = pd.read_csv(file_path)

 

Step 6: Print the dataframe data to console. For example, below snippet print first 5 rows and 4 columns of the dataframe.

 

print(df.iloc[:5, :4] )

 

Find the below working application.

 

hello_world.py

# Import the pandas Library.
import pandas as pd

# Specify the file path to the CSV file relative to the project directory.
file_path = '../../data/csv/ipl_matches.csv'

# Set the maximum number of columns to display as unlimited
pd.set_option('display.max_columns', None)

# Read the CSV file into a DataFrame
df = pd.read_csv(file_path)

print(df.iloc[:5, :4] )

 

Output

       id        city        date player_of_match
0  335982   Bangalore  2008-04-18     BB McCullum
1  335983  Chandigarh  2008-04-19      MEK Hussey
2  335984       Delhi  2008-04-19     MF Maharoof
3  335985      Mumbai  2008-04-20      MV Boucher
4  335986     Kolkata  2008-04-20       DJ Hussey

 

Total project structure looks like below.


 

 

 

 

 

Previous                                                 Next                                                 Home

Saturday, 16 September 2023

Data buffers in Python

Data buffer is a contiguous block of memory, used to store the data. Here the data can be of any type like integers, floating-point numbers, characters, or even more complex data structures like arrays or strings.

 

NumPy arrays internally use data buffers to perform the vector computations faster.

 

Advantages of Data buffers

a.   Faster data access: since the data buffer store the in contiguous memory locations, it is very efficient to access the data and perform numeric computations on it.

b.   Less memory overhead: Data buffers are homogeneous. That means all the elements of the data buffer are of same type. Because of this homogeneous nature, data buffers do not need to store the data type of each element.

 

data_buffer.py

import array

# Create an array of 32-bit integers
my_buffer = array.array('i', [1, 2, 3, 4, 5])

# Access elements in the buffer
element = my_buffer[2]
print('element at location 2 is : ', element)

# Modify an element in the buffer
my_buffer[1] = 99
print(my_buffer)  # Output: array('i', [1, 99, 3, 4, 5])

 


Output

element at location 2 is :  3
array('i', [1, 99, 3, 4, 5])

 

Previous                                                 Next                                                 Home

Thursday, 14 September 2023

Pandas: A Guide to Traversing Series

In this post, I am going to explain different ways to traverse the Pandas Series.

Approach 1: Using for loop and series index attribute.

for index_label in series.index:
    value = series[index_label]
    print(f"Index: {index_label}, Value: {value}")

Approach 2: Using enumerate method.

for index_position, index_label in enumerate(series.index):
    print(f"Index: {index_position}, Label: {index_label}, Value: {series[index_label]}")

Approach 3: Using series items method.

for index_label, value in series.items():
    print(f"Index: {index_label}, Value: {value}")

traverse_series.py

import pandas as pd

primes_list = [2, 3, 5, 7]
index_labels = ['A', 'B', 'C', 'D']
series = pd.Series(primes_list, index=index_labels)

# Using for loop and series index attribute.
print('Using for loop and series index attribute.')
for index_label in series.index:
    value = series[index_label]
    print(f"Index: {index_label}, Value: {value}")

# Using enumerate method
print('\nUsing for loop and series index attribute.')
for index_position, index_label in enumerate(series.index):
    print(f"Index: {index_position}, Label: {index_label}, Value: {series[index_label]}")

# Using series items method
print('\nUsing series items method')
for index_label, value in series.items():
    print(f"Index: {index_label}, Value: {value}")

Output

Using for loop and series index attribute.
Index: A, Value: 2
Index: B, Value: 3
Index: C, Value: 5
Index: D, Value: 7

Using for loop and series index attribute.
Index: 0, Label: A, Value: 2
Index: 1, Label: B, Value: 3
Index: 2, Label: C, Value: 5
Index: 3, Label: D, Value: 7

Using for loop and series index attribute.
Index: A, Value: 2
Index: B, Value: 3
Index: C, Value: 5
Index: D, Value: 7


Previous                                                 Next                                                 Home

How to Connect Members of Two Classes in PlantUML

We can connect the fields of two classes using an arrow.

 

Example

Employee::addressId --> Address::id : foreign key

 

Above snippet connect the fields addressId of Employee class with the id field of Address class and label as ‘foreign key’.

 

connectMembers.txt

@startuml

class Employee{
	+int id
	+String name
	+int addressId
}

class Address{
	+int id
	+String country
	+String state
	+String city
	+int employeeId
}

Employee::addressId --> Address::id : foreign key
Address::employeeId --> Employee::id : foreign key

@enduml

 

Above snippet generate below diagram.


 

Previous                                                    Next                                                    Home