Uncategorized

24:Data Analytics

Data Analytics

Data is new petroleum. All tech companies want to collect data of their customers to fine tune their products and advertisement campaigns. Data analytics is the requirement of all trade including social sciences, engineering, marketing and management, health care and artificial intelligence. The reason behind the popularity of Python is that this language is widely adopted by data analysts rather than software developers. In this lecture we will understand how to perform simple data analytics in Python. The important thing is, you must know basic statistics for data analytics.

  1. Data analytics is a vast field because it belongs to every trade.
  2. In every trade, there are specific operations like in marketing, we have to find how our sales are performing and how we can increase them. In medicine, we have to analyze the disease and how to cure it, in engineering it is required to measure the performance of an engine etc.
  3. Following steps are required to perform Data Analytics.
  4. Data Acquisition: Gather the data for analysis like sales and customer record of a product. The collection of data after gathering is called Data Set
  5. Data Cleaning: Sometimes invalid data or incorrect information may be included in our data set that can affect our analysis.
  6. Exploration of Data: This is an actual data analytics step.
  7. Visualization: This is the part of exploration that generates graphs to see the data in picture format.
  8. Classification and Regression: We have required distribution of data items into different classifications and evaluate the prediction.
  9. The last step (Classification and Regression) is the part of machine learning and we will discuss it in the next lecture.
  10. Python has the most powerful libraries for data analytics. Some of them are following
  11. Pandas: This library provides functions that work as simple calculators for data. This library has specialized data types for analytics.
  12.  Numpy: This library provides a large set of statistical and mathematical functions.
  13. Mat Plot Lib: Use for graph generations.
  14. Seaborn: Advance graph generation.
  15. Sk Learn: Use for classification and prediction (machine learning).
  16. The data we use as an example in this lecture is a simple CSV file but in actual projects, we have to use a variety of data like text, excel sheets, pdf, images, audio, video or something else.
  17. CSV (Comma Separated Values) is a simple text file structure where data records are defined in rows and elements of each record are separated by comma (,) delimiter.
  18. You can also open CSV in Excel Sheets.

Figure 1: Sales Record in CSV

  1. This is a simple sales record of 10 sales.
  2. Following attributes of each record are collected.
  3. CustomerID
  4. CustomerName
  5. Age
  6. Gender
  7. City
  8. PurchaseAmount
  9. ProductCategory
  10. These attributes are defined in the first row and separated by comma.
  11. Next ten lines belong to actual records of 10 customers and each value in the record is also separated by comma.
  12. Though this file contains only 10 records, in real world projects this file can hold millions of records and we may have to use hundreds of files of such records.
  13. Similarly, there are only 7 attributes but in actual these may be hundreds.
  14. We can use open and read functions to get data from this csv but it will increase the typing effort and also reduce the efficiency.
  15. We will use pandas and matplotlib libraries because our project is quite simple.
  16. If one or both libraries are not installed on your computer then run the following command to get pandas.
  17. Types this command in Terminal.
pip install pandas

Code 1: Installing pandas

  1. It will download and install the pandas.
  2. It takes a few moments to complete.

Figure 2:Downloading and Installation Process of Pandas

  1. Similarly, if matplotlib is not available then install it too.
  2. After installation of both libraries, run the following code.
import pandas as pd df = pd.read_csv ('customer_purchases.csv')print(df)

Code 2: Loading CSV file and getting Data

  1. The pandas library function read_csv will read the given CSV file and return a DataFrame object.
  2. The DataFrame is a special kind of variable that holds the CSV data in the form of rows and columns.
  3. On print we will find a sophisticated table like this.

Figure 3: Printing DataFrame

  1. It automatically, consider the first row a column names and all other rows as data
  2. By printing the DataFrame , we found that some values are not proper in this data and they are filled with NaN.
  3. The customers Sara and Ayesha missing purchase amount and Hina age is missing.
  4. There are many solutions for it. We can put zeros here, we can remove the faulty rows from DataFrame or we can put average value here.
  5. Some other solutions can be applied.
  6. We decide to use average to fill the empty or NaN values.
df["Age"].fillna(df["Age"].mean(), inplace=True)df["PurchaseAmount"].fillna(df["PurchaseAmount"].mean(), inplace=True)print(df)

Code 3: Cleaning Data with mean()

  1. This is one of the cleaning methods. It will take the mean value of a given column and put it in the place of NaN values. inplace=True will update the DataFrame and will not generate a new copy.
  2. On line 1, we update the Age column and on line 2, we update the PurchaseAmount column.
  3. If required to keep both copies (DataFrame with NaN values and filled values) then we can set it False and return a new DataFrame.
df2 = df.fillna(df["Age"].mean(), inplace=False)

Code 3: Old DataFrame will not be updated

  1. It will create a new copy and save data in df2.
  2. The output of code 2 will be followed.

Figure 4: Putting average values of respected columns in NaN

  1. Statistically Describing data is a very general method to understand it. We calculate the following values in it. Normally, describe operations performed on numerical values.
  2. Count: Number of values in columns.
  3. Mean: Average of the values.
  4. Standard Deviation: Standard Deviation of numerical columns.
  5. Min: Minimum value.
  6. Max: Maximum value.
  7. 25%, 50%, 75%: Percentile of values.
print (df.describe())

Code 4: Printing Statistical Description of Data

Figure 5: Statistical Description of Data

  1. Consider that code also includes CustomerID while it is just an identification number. We don’t need to add it in statistics of data.
  2. “A picture is better than a thousand words”. This old saying is still valid for data analysis.
  3. We can graph the sales in different Product Categories.
  4. To show data on a graph is called Data Visualization.
  5. Now draw a graph that shows required data.
  6. To draw graphs, we required matplotlib to import
import matplotlib.pyplot as plt

Code 5: Importing Plot Library

  1. Now we will write the code that displays a graph with the sum of the amount spent in each category. It should be a bar graph and we can find which category has more amount.
total_spending = df.groupby('ProductCategory')['PurchaseAmount'].sum()plt.bar(total_spending.index, total_spending.values, color=['red', 'green', 'blue'])plt.title('Total Purchase Amount by Category')plt.xlabel(Category')plt.ylabel('Total Purchase Amount')plt.tight_layout()plt.show()

Code 6: Code for Bar Graph by Category

  1. First, we create groups of data by using groupby function of DataFrame.
  2. We provided a string parameter which is the name of the category column.
  3. It returns another DataFrame and we select a column PurchaseAmount and get the sum.
  4. This will return a series object that contains the categories wise sum of purchase.
  5. By using plt, first, we define that it will be a vertical bar graph by bar function.
  6. The first argument we provide, uses an element on the x-axis. Here we provide it index of total_spending. The category names are stored in the index of the series.
  7. The next parameter is the height of each element on the x-axis. We want to show the amount of each element which is stored in total_spending.values.
  8. Finally, we provide some esthetics to differentiate the data and provide a list of colors. First category will be shown in Red, second will be in Green and third will be in Blue.
  9. title() is the main title of the graph.
  10. xlabel() will show on x-axis. We want to show the Category here
  11. ylabel() will show on y-axis. We want to show the amount.
  12. tight_layout() means graph elements look close to each other.
  13. plt.show() display the graph.

Figure 6: Category wise spending

This graph shows that Clothing is the highest category and more than Rs. 8000 spent in this category, electronics is second highest and little bit less than Rs. 8000 while groceries remain about Rs. 6000.

Leave a Reply

Your email address will not be published. Required fields are marked *