Thursday, 21 September 2023

How to Change the Size of Markers in Scatter Plots?

Using the parameter ‘s’ of pyplot scatter method, we can customize the size of markers in a scatter plot. You can set a single value or array of values.

 

Example

marker_sizes = [((n/min_value) *50) for n in salary]
plt.scatter(age, salary, label="Employees salaries plot", s=marker_sizes)

 

Find the below working application.

 

increase_marker_size.py

import matplotlib.pyplot as plt
import numpy as np

age = [34, 35, 31, 36, 45, 23, 51, 29, 32, 30, 34]
salary = [200000, 450000, 55000, 150000, 550000, 600000, 350000, 450000, 95000, 495000, 425000]
min_value = min(salary)

marker_sizes = [((n/min_value) *50) for n in salary]
plt.scatter(age, salary, label="Employees salaries plot", s=marker_sizes)

plt.xlabel('Age')
plt.ylabel('Salary')
plt.title('Scatter Plot Example')

plt.legend()
plt.show()

 

Output


 

 

 

Previous                                                    Next                                                    Home

Pandas: Understanding the Dataframe index attribute

Dataframe index attribute specifies the index labels assigned to each row.

dataframe_index.py

import pandas as pd

# Create a sample DataFrame
data = {'Name': ['Krishna', 'Ram', 'Joel', 'Gopi', 'Jitendra', "Raj"],
        'Age': [34, 25, 29, 41, 52, 23],
        'City': ['Bangalore', 'Chennai', 'Hyderabad', 'Hyderabad', 'Bangalore', 'Chennai']}

df = pd.DataFrame(data)

# Access the index attribute
index_labels = df.index

print(index_labels)

Output

RangeIndex(start=0, stop=6, step=1)

The index attribute (df.index) returns a RangeIndex object, which represents the range of index labels from the start value (0) to the stop value (6) with a step of 1.

 

We can traverse the elements of DataFrame using RangeIndex.

 

range_index.py

import pandas as pd

# Create a sample DataFrame
data = {'Name': ['Krishna', 'Ram', 'Joel', 'Gopi', 'Jitendra', "Raj"],
        'Age': [34, 25, 29, 41, 52, 23],
        'City': ['Bangalore', 'Chennai', 'Hyderabad', 'Hyderabad', 'Bangalore', 'Chennai']}

df = pd.DataFrame(data)

# Access the index attribute
index_labels = df.index
print(index_labels)

print("\nTaverse the dataframe using RangIndex")
for index_label in index_labels:
    row = df.loc[index_label]
    print(row, "\n")

Output

RangeIndex(start=0, stop=6, step=1)

Taverse the dataframe using RangIndex
Name      Krishna
Age            34
City    Bangalore
Name: 0, dtype: object 

Name        Ram
Age          25
City    Chennai
Name: 1, dtype: object 

Name         Joel
Age            29
City    Hyderabad
Name: 2, dtype: object 

Name         Gopi
Age            41
City    Hyderabad
Name: 3, dtype: object 

Name     Jitendra
Age            52
City    Bangalore
Name: 4, dtype: object 

Name        Raj
Age          23
City    Chennai
Name: 5, dtype: object

In the above example, for loop iterates over the DataFrame RangeIndex. Inside the loop, df.loc[index_label] is used to access each row of the DataFrame by its index label index_label.


Previous                                                 Next                                                 Home

How to Pretty Print DataFrames in Pandas?

Using ‘tabulate’ module, we can pretty print the data frame content.

Example

table = tabulate(df, headers='keys', tablefmt='pretty')

 

‘tabulate()’ function takes the DataFrame ‘df’ as the first argument. I specified the headers parameter as 'keys' to use the column names as the table headers and the tablefmt parameter is set to 'pretty' to generate a pretty print table.

 

pretty_print.py

import pandas as pd
from tabulate import tabulate

# Create a sample DataFrame
data = {'Name': ['Krishna', 'Sailu', 'Joel', 'Chamu', 'Jitendra', "Krishna"],
        'Age': [34, 35, 29, 35, 52, 34],
        'City': ['Bangalore', 'Hyderabad', 'Hyderabad', 'Chennai', 'Bangalore', 'Chennai'],
        'Gender': ['Male', 'Female', 'Male', 'Female', 'Male', 'Male'],
        'Education': ['Graduate', 'Post Graduate', 'PHD', 'Graduate', 'Graduate', 'Intermediate']}
df = pd.DataFrame(data)
print('Original DataFrame')
print(df)

table = tabulate(df, headers='keys', tablefmt='pretty')
print('\ntable\n',table)

 

Output

Original DataFrame
       Name  Age       City  Gender      Education
0   Krishna   34  Bangalore    Male       Graduate
1     Sailu   35  Hyderabad  Female  Post Graduate
2      Joel   29  Hyderabad    Male            PHD
3     Chamu   35    Chennai  Female       Graduate
4  Jitendra   52  Bangalore    Male       Graduate
5   Krishna   34    Chennai    Male   Intermediate

table
 +---+----------+-----+-----------+--------+---------------+
|   |   Name   | Age |   City    | Gender |   Education   |
+---+----------+-----+-----------+--------+---------------+
| 0 | Krishna  | 34  | Bangalore |  Male  |   Graduate    |
| 1 |  Sailu   | 35  | Hyderabad | Female | Post Graduate |
| 2 |   Joel   | 29  | Hyderabad |  Male  |      PHD      |
| 3 |  Chamu   | 35  |  Chennai  | Female |   Graduate    |
| 4 | Jitendra | 52  | Bangalore |  Male  |   Graduate    |
| 5 | Krishna  | 34  |  Chennai  |  Male  | Intermediate  |
+---+----------+-----+-----------+--------+---------------+

 


Previous                                                 Next                                                 Home

How to Get the Last N Rows of a DataFrame in Pandas

 Dataframe tail method return last n rows of the dataframe.

 

Example

df.tail()

 

If you do not pass any argument to the tail method, then it return last 5 row.

 

df.tail(3)

Above snippet return last 3 rows.

 

For negative values of `n`, this function returns all rows except the first `n` rows.

except_first_2_rows = df.tail(-2)

 

Find the below working application.

 

last_n_rows.py

import pandas as pd

# Create a sample DataFrame
data = {'Name': ['Krishna', 'Ram', 'Joel', 'Gopi', 'Jitendra', "Raj"],
        'Age': [34, 25, 29, 41, 52, 23],
        'City': ['Bangalore', 'Chennai', 'Hyderabad', 'Hyderabad', 'Bangalore', 'Chennai']}

df = pd.DataFrame(data)

last_5_rows = df.tail()
print("last_5_rows : \n", last_5_rows)

last_3_rows = df.tail(3)
print("\nlast_3_rows : \n", last_3_rows)

except_first_2_rows = df.tail(-2)
print("\nexcept_first_2_rows : \n", except_first_2_rows)

 

Output

last_5_rows : 
        Name  Age       City
1       Ram   25    Chennai
2      Joel   29  Hyderabad
3      Gopi   41  Hyderabad
4  Jitendra   52  Bangalore
5       Raj   23    Chennai

last_3_rows : 
        Name  Age       City
3      Gopi   41  Hyderabad
4  Jitendra   52  Bangalore
5       Raj   23    Chennai

except_first_2_rows : 
        Name  Age       City
2      Joel   29  Hyderabad
3      Gopi   41  Hyderabad
4  Jitendra   52  Bangalore
5       Raj   23    Chennai

 

  

Previous                                                 Next                                                 Home

How to Model Aggregation Relationships in Object Diagrams with PlantUML?

Aggregation relationship is modeled using the symbol o—

 

objectAggregation.txt

@startuml

title "Object Aggregation"

object "My:Car" as myCar

object "My:Engine" as myEngine
object "My:Transmission" as myTransmission
object "My:Battery" as myBattery
object "My:Alternator" as myAlternator
object "My:Radiator" as myRadiator
object "My:Brakes" as myBrakes
object "My:FuelTank" as myFuelTank

object "My:Piston" as myPiston
object "My:Flywheel" as myFlywheel
object "My:Gasket" as myGasket

myCar o-- myEngine
myCar o-- myTransmission
myCar o-- myBattery
myCar o-- myAlternator
myCar o-- myRadiator
myCar o-- myBrakes
myCar o-- myEngine
myCar o-- myFuelTank

myEngine o-- myPiston
myEngine o-- myFlywheel
myEngine o-- myGasket

@enduml

Above snippet generate below diagram.



 

 

Previous                                                    Next                                                    Home

How to Define Composition Relationships in Object Diagrams with PlantUML?

Composition relationship is modeled using the symbol *--

 

composition.txt

@startuml

title "Object Composition"

object "My:Brain" as brain

object "My:Frontal" as frontal
object "My:Parietal" as parietal
object "My:Temporal" as temporal
object "My:Occipital" as occipital

brain *-- frontal
brain *-- parietal
brain *-- temporal
brain *-- occipital

@enduml

 

Above snippet generate below diagram.

 


 

Previous                                                    Next                                                    Home

How to Model Extension Relationships in Object Diagrams with PlantUML

Symbol <|-- models the extension relationship in object diagram.

extension.txt

@startuml

object "Parent:Person" as parent
object "Child:Person" as child

parent <|-- child : Inherit from

@enduml

 Above snippet generate below diagram.

  


Previous                                                    Next                                                    Home