Sunday, 29 October 2023

Replace missing or NaN values in a Pandas DataFrame

We can fill the missing values in a DataFrame using fillna method.

Example

df_without_missing_values = df.fillna(0)

 

Above snippet replace all the missing values with 0 and assign the dataset to the variable ‘df_without_missing_values’, but do not affect the original DataFrame.

 

To update the changes in original DataFrame, you can set the argument inplace to True.

 

df.fillna(0, inplace=True)

 

Find the below working application.

 

fill_missing_values.py

import pandas as pd
import numpy as np

# Create a sample DataFrame
data = {
    'A' : [1, 2, np.nan, 3, 4, np.nan, 5],
    'B' : [1, np.nan, np.nan, 3, 4, 5, 6],
    'C' : [1, 2, np.nan, 4, 5, np.nan, 6],
    'D' : ['a', 'b', None, None, 'c', 'd', 'e']
}

df = pd.DataFrame(data)
df_without_missing_values = df.fillna(0)

print('Original DataFrame')
print(df)

print('\nDataFrame by filling with 0')
print(df_without_missing_values)

df.fillna(0, inplace=True)
print('\nOriginal DataFrame by filling with the argument inplace=True')
print(df)

Output

Original DataFrame
     A    B    C     D
0  1.0  1.0  1.0     a
1  2.0  NaN  2.0     b
2  NaN  NaN  NaN  None
3  3.0  3.0  4.0  None
4  4.0  4.0  5.0     c
5  NaN  5.0  NaN     d
6  5.0  6.0  6.0     e

DataFrame by filling with 0
     A    B    C  D
0  1.0  1.0  1.0  a
1  2.0  0.0  2.0  b
2  0.0  0.0  0.0  0
3  3.0  3.0  4.0  0
4  4.0  4.0  5.0  c
5  0.0  5.0  0.0  d
6  5.0  6.0  6.0  e

Original DataFrame by filling with the argument inplace=True
     A    B    C  D
0  1.0  1.0  1.0  a
1  2.0  0.0  2.0  b
2  0.0  0.0  0.0  0
3  3.0  3.0  4.0  0
4  4.0  4.0  5.0  c
5  0.0  5.0  0.0  d
6  5.0  6.0  6.0  e

Fill the missing values in a specific column

 

df['City'] = df['City'].fillna('not_found')

Above statement fill the missing values in ‘City’ column with the value ‘not_found’

 

df['Age'].fillna(0, inplace=True)

Above statement fill the missing values in ‘Age’ column with the value 0.

 

Find the below working application.

 

fill_missing_values_in_a_column.py

import pandas as pd
import numpy as np

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

df = pd.DataFrame(data)
print(df)

df['City'] = df['City'].fillna('not_found')
df['Age'].fillna(0, inplace=True)

print('\nAfter filling missing values')
print(df)

Output

       Name   Age       City
0   Krishna  34.0  Bangalore
1       Ram   NaN       None
2      Joel  29.0  Hyderabad
3      Gopi  41.0       None
4  Jitendra  52.0  Bangalore
5       Raj   NaN    Chennai

After filling missing values
       Name   Age       City
0   Krishna  34.0  Bangalore
1       Ram   0.0  not_found
2      Joel  29.0  Hyderabad
3      Gopi  41.0  not_found
4  Jitendra  52.0  Bangalore
5       Raj   0.0    Chennai


  

Previous                                                 Next                                                 Home

Adding Grid Lines to Plots in Matplotlib

Using grid method of Pyplot, we can display grid lines on a plot.

Signature

matplotlib.pyplot.grid(b=None, which='major', axis='both', **kwargs)

 

b: If the parameter b is set to True, then it displays grid lines on the plot. If the parameter b is set to False, then grid lines are hidden. By default it is set to None, and the default state depends on  the current state of the grid.

 

which: Specifies which kind of grid lines the settings should apply. Possible values are major, minor and both.

 

axis: It can take one of three values.

1.   both: Apply grid lines to both the axis

2.   x: Apply grid lines to x-axis

3.   y: Apply grid lines to y-axis

 

Apart from this you can specify the arguments like color, linestyle, alpha parameters (alpha parameter control the transparency or opacity of graphical elements).

 

Example 1: Plot grid lines on both x and y axis.

plt.plot(x, y, label='y = 10 * x + 123')

 

add_grid_lines.py

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(1, 10)
y = 10 * x + 123

plt.plot(x, y, label='y = 10 * x + 123')

plt.grid(True)
plt.show()

 

Output

 


Example 2: Add only horizontal grid lines.

plt.grid(True, axis='y')

 

add_horizontal_grid_lines_only.py

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(1, 10)
y = 10 * x + 123

plt.plot(x, y, label='y = 10 * x + 123')

plt.grid(True, axis='y')
plt.show()

Output


 

Example 3: Customize grid line style, color, opacity.

plt.grid(True, linestyle='--', color='red', alpha=0.5)

 

customize_grid_line.py

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(1, 10)
y = 10 * x + 123

plt.plot(x, y, label='y = 10 * x + 123')

plt.grid(True, linestyle='--', color='red', alpha=0.5)
plt.show()

 

Output

 


 

Example 4: ‘which’ parameter example.

 

You need to turn on minor tick by executing below line.

plt.minorticks_on()

 

Find the below working application.

 

which_parameter.py

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(1, 100)
y = 10 * x + 123

plt.plot(x, y)

plt.minorticks_on()

# Customize major gridlines only
plt.grid(True, which='major', linestyle='--', color='red')

# Customize minor gridlines only
plt.grid(True, which='minor', linestyle=':', color='blue')

# Show the plot
plt.show()

Output



 

 

Previous                                                    Next                                                    Home

How to Add Vertical Lines to Plots in Python with Matplotlib?

Using 'axvline' method, we can draw a vertical line on the plot.

Example

plot.axvline(x=100, color='red', label=f'Vertical Line at x={100}')

 

Above statement draws a vertical line at x=100, and applies red color to it.

 

Find the below working application.

 

vertical_line.py

import matplotlib.pyplot as plot
import numpy as np

# Sample data
x = np.arange(1, 100)
y = 10 * x + 123

# Plot the data points
plot.plot(x, y, label='y=10x+123')

median = np.median(x)

plot.axvline(x=median, color='red', label=f'Vertical Line at x={median}')
text = f'This is x={median}'
plot.text(median+15, 1000, text, color='red', fontsize=12, ha='center')

# Set labels and legend
plot.legend()

# Show the plot
plot.show()

 

Output

 


 

Previous                                                    Next                                                    Home

Plotting Horizontal Lines in Matplotlib with Pyplot

Using 'axhline' method, we can draw horizontal line on a plot

Example

plot.axhline(y=100, color='green', label=f'Horizontal Line at y=100')

Above statement draws a horizontal line at y = 100, and applies green color to it.

 

Find the below working applicaiton.

 

horizontal_line.py

import matplotlib.pyplot as plot
import numpy as np

# Sample data
x = np.arange(1, 100)
y = 10 * x + 123


# Plot the data points
plot.plot(x, y, label='y=10x+123')

mean = np.mean(y)
plot.axhline(y=mean, color='green', label=f'Horizontal Line at y={mean}')
text = f'This is y={mean}'
plot.text(30, mean + 10, text, color='red', fontsize=12, ha='center')

# Set labels and legend
plot.legend()

# Show the plot
plot.show()

Output



 

  

Previous                                                    Next                                                    Home

PlantUML: Add Labels to Activity Diagram Arrows

Using ->, ; you can add text to the arrow.

 

Example

->This is arrow1 description;

 

addTextToArrow.txt

@startuml

start

:Activity1;
->This is arrow1 description;

:Activity2;
->This is arrow2
multi line description;

:Activity3;
->This is arrow3
multi line description;

stop

@enduml

 

Above snippet generate below diagram.

 


 

Previous                                                    Next                                                    Home

Thursday, 12 October 2023

PlantUML: Activity Diagrams Without Arrows

Using the command 'skinparam ArrowHeadColor none', we can connect activities using lines only (no arrows).

noArrowLines.txt

@startuml

skinparam ArrowHeadColor none
start

:Activity1;
:Activity2;
:Activity3;

stop

@enduml

 

Above snippet generate below diagram.


 

  

Previous                                                    Next                                                    Home

PlantUML: Customizing Activity Appearance

 By changing the activity end (;) to either of following symbols, we can customize the activity.

 

a.   |

b.   < 

c.    > 

d.   /

e.   \\

f.     ]

g.   }

 

renderDifferently.txt

@startuml

start

:My activity1;
:My activity2|
:My activity3<
:My activity4>
:My activity5/
:My activity6\\
:My activity7]
:My activity8}

stop

@enduml

Above snippet generate below diagram.

 


Previous                                                    Next                                                    Home