During my years as a Consultant Data Scientist I have received many requests from my clients to provide frequency distribution reports for their specific business data needs. These reports have been very useful for the company management to make proper business decisions quickly. In this paper I would like to show how to design and develop a generic frequency distribution library that will allow you to reduce your development time and provide a good summary table and image report for your clients. One important topic to be covered is this paper is a logic conversion of a top-bottom Python code in a generic reusable super class library for future Object-Oriented Programming (OOP) development applied data analytics and visualization.

I’ll be using the following three main Python Data Stack libraries:

    1. NumPyis the fundamental package for scientific computing.
    2. pandas – is an open source library, providing high-performance, easy-to-use data structures and data analysis tools
    3. Matplotlibis a Python 2D plotting library which produces publication quality figures in a variety of hardcopy formats and interactive environments across platforms.

Frequency Statistical Definitions

The frequency of a particular data value is the number of times the data value occurs. A frequency distribution is a tabular summary (frequency table) of data showing the frequency number of observations (outcomes) in each of several non-overlapping categories named classes. The objective is to provide a simple interpretation about the data that cannot be quickly obtained by looking only at the original raw data.

The Frequency Distribution Analysis can be used for Categorical (qualitative) and Numerical (quantitative) data types. I have seen the most use of it for Categorical data especially during the data cleansing process using pandas library. In general, there are  two types of frequency tables, Univariate (used with a single variable) and Bivariate (used with multiple variables). Univariate tables will be used in this paper. The Bivariate frequency tables are presented as (two-way) Contingency Tables. These tables are used in Chi-squared Test Analysis for the Goodness-Of-Fit Test and Test of Independence. We’ll be covering these topics in future papers.

Network Server Activities Frequency Distribution Analysis

The windows network server activities log file (network_activities.csv) is provided in Table 1.

Time Priority Category Message
10:47.2 Info Firewall Event SonicWALL initializing
10:55.2 Error Firewall Event Interface X0 Link Is Down
10:55.2 Warning Firewall Event Interface X1 Link Is Up
10:55.2 Error Firewall Event Interface X2 Link Is Down
10:55.2 Info Authenticated Access Administrator login allowed
10:55.2 Error Firewall Event Interface X4 Link Is Down
10:55.2 Alert Intrusion Prevention Possible port scan detected
10:55.2 Error Firewall Event Interface X6 Link Is Down
10:55.2 Info Authenticated Access GUI administration session ended
10:55.2 Error Firewall Event Interface X8 Link Is Down
10:55.2 Error Firewall Event Interface X9 Link Is Down
11:02.2 Alert Firewall Event SonicWALL activated
33:20.4 Warning Firewall Event Interface X8 Link Is Up
33:23.4 Warning Firewall Event Interface X9 Link Is Up
33:56.0 Error Firewall Event Interface X8 Link Is Down

Table 1. Fifteen rows of network activities log file.

As you can see from Table 1, the log data file contains four columns as Time, Priority, Category and Message. In real production environment this log file may have hundreds of thousands of rows.

Network Server Activities Analysis

The server administrator team has requested a statistical analysis and report of the networking activities to be created for maintenance and management review. In general, this frequency statistical report includes two components:

  1. Frequency Summary Table
  2. Percent Frequency Distribution Chart

The Code Listing 1 shows a simple top-bottom Python code for Frequency Distribution Analysis.


  1. import sys
  2. import os
  3. import time
  4.  
  5. import numpy as np
  6. import pandas as pd
  7. import matplotlib.pyplot as plt
  8.  
  9. def main():
  10.  
  11. # Frequency Distribution 1 (Vertical Bar Chart)
  12. ----------------------------------------------------------------------------------------------------
  13.  
  14. # set file path name
  15. file_path_name = r"C:\Users\Ernest\git\test-code\test-code\src\percent_frequency_distribution\network_activities.csv"
  16.  
  17. # set image path name
  18. image_path_name1 = r"C:\Users\Ernest\git\test-code\test-code\src\percent_frequency_distribution\network_activities.png"
  19.  
  20. # get network activity data frame
  21. df_network_activity1 = pd.read_csv(filepath_or_buffer = file_path_name, sep = ",")
  22.  
  23. # get relative frequencies in a pandas serie
  24. ds_network_activity1 = df_network_activity1["Priority"].value_counts(normalize = True)
  25. print(ds_network_activity1)
  26.  
  27. # define the x and y axis’s
  28. x_axis = []
  29. y_axis = []
  30. for x, y in ds_network_activity1.iteritems():
  31. x_axis.append(x)
  32. y_axis.append(y * 100)
  33.  
  34. # build and plot the network activity vertical bar chat
  35. colors = []
  36. for x_value in x_axis:
  37. if x_value == "Error":
  38. colors.append('r')
  39. elif x_value == "Warning":
  40. colors.append('y')
  41. else:
  42. colors.append('g')
  43. plt.style.use("ggplot")
  44. x_pos = np.arange(len(x_axis))
  45. rects = plt.bar(x_pos, y_axis, width = 0.7, color = colors, align = "center", alpha = 0.7, label = "Amount of Messages")
  46. for rect in rects:
  47. rec_x = rect.get_x()
  48. rec_width = rect.get_width()
  49. rec_height = rect.get_height()
  50. height_format = float("{0:.1f}".format(rec_height))
  51. plt.text(rec_x + rec_width / 2, rec_height , str(height_format) + "%", horizontalalignment = "center", verticalalignment = 'bottom')
  52. plt.xticks(x_pos, x_axis)
  53. plt.xlabel("Priority")
  54. plt.ylabel("Percent Frequency")
  55. plt.title("Priority Message Percent Frequency Distribution")
  56. plt.legend(loc = 1)
  57. plt.tight_layout()
  58. plt.savefig(image_path_name1, dpi = 100)
  59. plt.show()
  60.  
  61. # Frequency Distribution 2 (Horizontal Bar Chart)
  62. -------------------------------------------------------------------------------------------------
  63.  
  64. # set image file path name
  65. image_path_name2 = r"C:\Users\Ernest\git\test-code\test-code\src\percent_frequency_distribution\network_activities2.png"
  66.  
  67. # get network activity data frame for priority and message columns
  68. df_network_activity2 = pd.read_csv(filepath_or_buffer = file_path_name, sep = ",")
  69.  
  70. # group by priority column
  71. df_column_group = df_network_activity2.groupby("Priority")
  72.  
  73. # get relative frequencies by message column
  74. ds_network_activity2 = df_column_group["Message"].value_counts(normalize = True)
  75.  
  76. # define the x and y axis’s
  77. x_axis = []
  78. y_axis = []
  79. for x, y in ds_network_activity2.iteritems():
  80. if x[0] == "Error":
  81. x_axis.append(x[1])
  82. y_axis.append(y * 100)
  83.  
  84. # build and plot the network activity horizontal bar chat
  85. plt.style.use("ggplot")
  86. x_pos = np.arange(len(x_axis))
  87. colors = ["r"]
  88. rects = plt.barh(x_pos, y_axis, color = colors, align = "center", alpha = 0.8, label = "Amount of Messages")
  89. for rect in rects:
  90. rec_y = rect.get_y()
  91. rec_width = int(rect.get_width())
  92. rec_height = rect.get_height()
  93. plt.text(rec_width - 0.6, rec_y + rec_height / 2, str(rec_width) + "%", horizontalalignment = "center", verticalalignment = 'bottom')
  94. plt.yticks(x_pos, x_axis)
  95. plt.xlabel("Percent Frequency")
  96. plt.ylabel("Error Message")
  97. plt.title("Error Server Percent Frequency Distribution")
  98. plt.legend(loc = 1)
  99. plt.tight_layout()
  100. plt.savefig(image_path_name2, dpi = 100)
  101. plt.show()
  102.  
  103. if __name__ == '__main__':
  104. start_time = time.time()
  105. main()
  106. end_time = time.time()
  107. print("Program Runtime: " + str(round(end_time - start_time, 1)) + " seconds" + "\n")

Code Listing 1. Top-bottom code for Frequency Distribution Analysis.

As you can see from this Code Listing 1 the majority of the input data has been hardcoding in the program and the only way to use this program is to copy and paste in another module file, and of course change the data input values after that – a lot works and a very bad programming practices for sure! Some of the input data hardcode are: data file and images paths, data column name, many plot parameters, etc.

I have seen many Python programmers doing this type of Data Analytics implementation using Python Jupyter Notebook or any modern text editor today. It’s like they don’t understand/know the importance of Object-Oriented Programming design and implementation, Continuous Integration deployment practices, Unit and System Tests, etc.

Frequency Distribution Main Library

We need to create a reusable and extensible library to considerably reduce the Data Analytics development time and necessary code. I have developed a frequency_distribution_superclass.py module that contains the frequency distribution class library FrequencyDistributionLibrary(object) shown in Code Listing 2.

  1. import os
  2. import sys
  3. import traceback
  4. import time
  5.  
  6. import numpy as np
  7. import pandas as pd
  8. import matplotlib.pyplot as plt
  9. import config
  10.  
  11. class FrequencyDistributionLibrary(object)
  12.  
  13.    """
  14.  
  15.    generic frequency distribution superclass library
  16.    """        
  17.    def __init__(self):
  18.        pass
  19.         
  20.    def print_exception_message(self, message_orientation = "horizontal"):
  21.  
  22.        """
  23.  
  24.        print full exception message
  25.  
  26.        :param message_orientation: horizontal or vertical
  27.  
  28.        :return none
  29.        """
  30.  
  31.        try:
  32.  
  33.            exc_type, exc_value, exc_tb = sys.exc_info()
  34. file_name, line_number, procedure_name, line_code = traceback.extract_tb(exc_tb)[-1]            
  35.   time_stamp = " [Time Stamp]: " + str(time.strftime("%Y-%m-%d %I:%M:%S %p"))
  36. file_name = " [File Name]: " + str(file_name)
  37. procedure_name = " [Procedure Name]: " + str(procedure_name)
  38. error_message = " [Error Message]: " + str(exc_value)        
  39. error_type = " [Error Type]: " + str(exc_type)                    
  40. line_number = " [Line Number]: " + str(line_number)                
  41. line_code = " [Line Code]: " + str(line_code)
  42. if (message_orientation == "horizontal"):
  43.  
  44.                print( "An error occurred:{};{};{};{};{};{};{}".format(time_stamp, file_name, procedure_name, error_message, error_type, line_number, line_code))
  45.            elif (message_orientation == "vertical"):
  46.                print( "An error occurred:\n{}\n{}\n{}\n{}\n{}\n{}\n{}".format(time_stamp, file_name, procedure_name, error_message, error_type, line_number, line_code))
  47.            else:
  48.                pass                    
  49.        except Exception:
  50.            pass
  51.  
  52.        
  53.    def get_project_directory_path(self):
  54.  
  55.        """
  56.  
  57.        get project directory path from the calling file
  58. """
  59.        project_directory_path = None
  60.        try:  
  61.            project_directory_path = os.path.dirname(sys.argv[0])            
  62.        except Exception:
  63.            self.print_exception_message()                    
  64.        return project_directory_path
  65.  
  66.  
  67.    def format_float_number(self, decimal_point, real_value):
  68.  
  69.        """
  70.        format float numbers with digits
  71. :param decimal_point:
  72.        :param real_value:
  73.        :return formatted float number
  74.        """
  75.        format_value = 0.0
  76.        try:
  77.            if decimal_point == 1:
  78.                format_value = float("{0:.1f}".format(real_value))
  79.            elif decimal_point == 2:
  80.                format_value = float("{0:.2f}".format(real_value))
  81.            elif decimal_point == 3:
  82.                format_value = float("{0:.3f}".format(real_value))
  83.            elif decimal_point == 4:
  84.                format_value = float("{0:.4f}".format(real_value))
  85.            elif decimal_point == 5:
  86.                format_value = float("{0:.5f}".format(real_value))
  87.            else:
  88.                format_value = float("{0:.3f}".format(real_value))
  89.        except Exception:                                                          
  90.            self.print_exception_message()
  91.        return format_value
  92.  
  93.  
  94.    def load_x_y_axis_data(self, data_file_name, column_name, group_by_colum = None, column_name_class = None):
  95.  
  96.        """
  97.        define x and y axis data
  98.        :param data_file_name:
  99.        :param column_name:
  100.        :param group_by_colum:
  101.        :return x and y axis data
  102.        """
  103.        x_axis = []
  104.        y_axis = []        
  105.        try:    
  106.            data_frame = pd.read_csv(filepath_or_buffer = data_file_name, sep = ",")         
  107.            if (group_by_colum is not None):                
  108.                data_frame = data_frame.groupby(group_by_colum)                                
  109.            data_serie = data_frame[column_name].value_counts(normalize = True)      
  110.            if (group_by_colum is not None):   
  111.                for x, y in data_serie.iteritems():     
  112.                    if x[0] == column_name_class:
  113.                        x_axis.append(x[1])           
  114.                        y_axis.append(self.format_float_number(1, y * 100))                                               
  115.            else:
  116.                for x, y in data_serie.iteritems():
  117.                    x_axis.append(x)        
  118.                    y_axis.append(self.format_float_number(1, y * 100))                            
  119.        except Exception:
  120.            self.print_exception_message()
  121.        return x_axis, y_axis
  122.  
  123.  
  124.    def print_summary_table(self, first_column_name, second_column_name, x_axis, y_axis):
  125.        """
  126.        print tabular summary table
  127.        :param first_column_name: class column
  128.        :param second_column_name: frequency numerical column
  129.        :param x_axis: x axis data
  130.        :param y_axis: y axis data
  131.        :return none
  132.        """
  133.        try:  
  134.            print("{}\t{}".format(first_column_name, second_column_name))
  135.            for x, y in zip(x_axis, y_axis):
  136.                print("{}\t\t{}".format(x, str(y) + "%"))
  137.        except Exception:
  138.            self.print_exception_message()
  139.         
  140.  
  141.    def build_bar_chart_vertical(self, x_axis, y_axis, image_file_name, plot_xlabel, plot_ylabel, plot_title, plot_legend):        
  142.  
  143.        """
  144.        build vertical bar chart
  145.        :param x_axis: x axis data
  146.        :param y_axis: y axis data
  147.        :param image_file_name: image file path and name
  148.        :return none
  149.        """
  150.        try:
  151.            colors = []
  152.            for x_value in x_axis:
  153.                if x_value == config.error_class:
  154.                    colors.append('r')
  155.                elif x_value == config.warning_class:
  156.                    colors.append('y')
  157.                else:
  158.                    colors.append('g')          
  159.            plt.style.use(config.plot_style)       
  160.            x_pos = np.arange(len(x_axis))         
  161.            rects = plt.bar(x_pos, y_axis, width = 0.7, color = colors, align = "center", alpha = 0.7, label = plot_legend)
  162.            for rect in rects:
  163.                rec_x = rect.get_x()
  164.                rec_width = rect.get_width()        
  165.                rec_height = rect.get_height()  
  166.                height_format = self.format_float_number(1, rec_height)      
  167.                plt.text(rec_x + rec_width / 2, rec_height , str(height_format) + "%", horizontalalignment = "center", verticalalignment = 'bottom')            plt.xticks(x_pos, x_axis)   
  168.            plt.xlabel(plot_xlabel)
  169.            plt.ylabel(plot_ylabel)      
  170.            plt.title(plot_title)    
  171.            plt.legend(loc = 1)    
  172.            plt.tight_layout()
  173.            plt.savefig(image_file_name, dpi = 100)
  174.            plt.show()       
  175.        except Exception:                                                          
  176.            self.print_exception_message()
  177.           
  178.  
  179.    def build_bar_chart_horizontal(self, x_axis, y_axis, image_file_name, plot_xlabel, plot_ylabel, plot_title, plot_legend):        
  180.  
  181.        """
  182.         build horizontal bar chart
  183.        :param x_axis: x axis data
  184.        :param y_axis: y axis data
  185.        :param image_file_name: image file path and name
  186.        :return none
  187.        """
  188.        try:  
  189.            plt.style.use(config.plot_style)  
  190.            x_pos = np.arange(len(x_axis))                     
  191.            colors = ["r"]    
  192.            rects = plt.barh(x_pos, y_axis, color = colors, align = "center", alpha = 0.8, label = plot_legend)    
  193.            for rect in rects:    
  194.                rec_y = rect.get_y()
  195.                rec_width = int(rect.get_width())
  196.                width_format = self.format_float_number(1, rec_width)   
  197.                rec_height = rect.get_height()        
  198.                plt.text(rec_width - 0.8,  rec_y + rec_height / 2, str(width_format) + "%", horizontalalignment = "center", verticalalignment = 'bottom')           
  199.            plt.yticks(x_pos, x_axis)   
  200.            plt.xlabel(plot_xlabel)
  201.            plt.ylabel(plot_ylabel)      
  202.            plt.title(plot_title)    
  203.            plt.legend(loc = 1)    
  204.            plt.tight_layout()
  205.            plt.savefig(image_file_name, dpi = 100)
  206.            plt.show()   
  207.        except Exception:                                                          
  208.  
  209.            self.print_exception_message()

Code Listing 2. Frequency distribution superclass FrequencyDistributionLibrary(object).

This library contains six main functions used in the paper for any complete Frequency Distribution Analysis:

  1. print_exception_message(self, message_orientation = “horizontal”)
  2. format_float_number(self, decimal_point, real_value)
  3. load_x_y_axis_data(self, data_file_name, column_name, group_by_colum = None, column_name_class = None)
  4. print_summary_table(self, first_column_name, second_column_name, x_axis, y_axis)
  5. build_bar_chart_vertical(self, x_axis, y_axis, image_file_name, plot_xlabel, plot_ylabel, plot_title, plot_legend)       
  6. build_bar_chart_horizontal(self, x_axis, y_axis, image_file_name, plot_xlabel, plot_ylabel, plot_title, plot_legend)     

In Part 2 we’ll be covering how to inherit from this library to create a subclass module. Real business examples of Frequency Distribution Analysis will be provided.

Previous post

Machine Learning using Spark and R

Next post

Big Data in Real Estate: Staying Ahead of the Curve