Sitemap

Python for Data Science

12 min readFeb 18, 2023

Press enter or click to view image in full size
Getting Started with Python

A Comprehensive Guide

Python

Data scientists prefer to use Python as their programming language. While Python was not the original primary language for data science, its popularity has steadily increased over time. Kaggle, which is a leading platform for data science competitions, reported that in 2016, Python became more widely used than R

Python is a popular programming language for data science due to its versatility, ease of use, and the availability of many powerful libraries for data analysis and machine learning. Python provides a simple and intuitive syntax, making it easy for data scientists to read and write code, as well as allowing for easy debugging and troubleshooting.

My approach toward learning python, I’m using this learning method. I named it CRUD. Basically, CRUD is a method I usually adopt for any technical learning.

C-Create

R-Read

U-Update

D-Delete

Instances,

#creating a list:

names = [‘halima’, ‘hardarb’, ‘odunola’, ‘maryam’, ‘elon musk’]

We can READ them using indexing or the print function

pythonCopy code

# Creating a list names = ['halima', 'hardarb', 'odunola', 'maryam', 'elon musk']

# Printing the list print(names)

# Reading the first value

print(names[0])

# Slicing a range

print(names[1:3])

To UPDATE, you can reassign a value, and use the insert method or append method.

# Updating a single value
names[-1] = ‘nicholas young’

# Updating by adding to the end of the list
names.append(‘elon musk’)

# Updating by inserting at the start of the list
names.insert(0, ‘mark manson’)

And last but certainly not least, it helps in understanding how to DELETE.

# Delete components from a list
del names[-2]

Data Categories

In order to analyze data, we must know the data we are dealing with.

Data can be split into three main categories:

  1. Numerical -Numerical data represent values that can be measured and put into a logical order. Examples of numerical data are height, weight, age, number of movies watched, IQ , etc. To graph numerical data, one uses dot plots, stem and leaf graphs, histograms, box plots, ogive graphs, and scatter plots.

Numerical Data/values can be divided into two categories:

  • Discrete: a type of quantitative data that includes non-divisible figures and statistics you can count. Numbers are counted as “whole”. Example: You cannot have trained 2.5 sessions, it is either 2 or 3
  • Continuous: data often show trends in data over time. Numbers can be of infinite precision. For example, you can sleep for 7 hours, 30 minutes, and 20 seconds, or 7.533 hours

2. Categorical -Categorical data is the statistical data comprising categorical variables of data that are converted into categories . One of the examples is grouped data Containing values that cannot be measured up against each other. Example: A color or a type of training

3. Ordinal -A distinguishing feature of ordinal data is that the categories it uses are ordered on some kind of hierarchical scale, e.g. high to low. Contains categorical data that can be measured up against each other. Example: School grades where A is better than B and so on

By knowing the type of your data, you will be able to know what technique to use when analyzing them.

Here are some of the key reasons why Python is so popular among data scientists:

  1. Libraries: Python has several powerful libraries for data analysis and machine learning, such as NumPy, Pandas, Scikit-learn, Matplotlib, and TensorFlow, among others. These libraries make it easy to perform complex data analysis tasks with just a few lines of code.
  2. Interoperability: Python can be used with other popular tools and technologies, such as Jupyter Notebooks, SQL, and Hadoop. This allows data scientists to use Python in conjunction with other tools to analyze, process, and visualize data.
  3. Community: Python has a large and supportive community of developers and users who share tips, resources, and best practices. This community is constantly developing new libraries, tools, and techniques to improve data analysis and machine learning with Python.
  4. Flexibility: Python is a flexible language that can be used for a wide range of applications beyond data science, such as web development, automation, and scientific computing. This makes it a useful language to learn for professionals in various fields.

Some common tasks that data scientists use Python for include:

  1. Data cleaning and preprocessing: Python has several libraries, such as Pandas, for cleaning and preprocessing data.
  2. Data visualization: Python offers libraries like Matplotlib and Seaborn that enable data scientists to create high-quality visualizations of their data.
  3. Machine learning: Python offers a variety of machine learning libraries, including Scikit-learn, TensorFlow, and Keras, that enable data scientists to build models to predict outcomes or classify data based on patterns.
  4. Natural Language Processing (NLP): Python offers several libraries for NLP such as NLTK, SpaCy, and Gensim, which enable data scientists to perform text classification, sentiment analysis, topic modeling, and other NLP tasks.

Python Libraries

Python has several libraries with large collections of mathematical functions and analytical tools, making it a popular language for scientific computing, data analysis, and machine learning. Some of the most commonly used libraries for mathematical functions and analytical tools in Python are:

  1. NumPy: NumPy is a library that provides support for large, multi-dimensional arrays and matrices. It also has a large collection of mathematical functions for array manipulation, linear algebra, Fourier transforms, and more.
  2. SciPy: SciPy is a library that builds on NumPy and provides additional functionality for optimization, integration, signal processing, linear algebra, and more.
  3. pandas: pandas is a library for data manipulation and analysis, providing tools for working with time-series data, data frames, and data visualization.
  4. Matplotlib: Matplotlib is a library for creating static, animated, and interactive visualizations in Python. It is commonly used for creating line plots, scatter plots, bar plots, and histograms.
  5. Seaborn: Seaborn is a library that builds on Matplotlib and provides a higher-level interface for creating statistical graphics, including heat maps, joint plots, and pair plots.
  6. SymPy: SymPy is a library for symbolic mathematics, providing tools for symbolic manipulation of mathematical expressions, calculus, algebra, and more.

These libraries are widely used in various fields, including engineering, finance, physics, and machine learning.

It is worth noting that, in python, the numbering of rows starts with zero.

Reason

Get Lymah’s stories in your inbox

Join Medium for free to get updates from this writer.

In Python, like in many other programming languages, the indexing of arrays and lists starts at 0, rather than 1. This means that the first element in an array or list is indexed as 0, the second element is indexed as 1, and so on.

The reason why indexing starts at 0 in Python is historical. In the early days of computing, programming languages such as Fortran and C were developed that used zero-based indexing. This approach was based on the way that memory was allocated and indexed in computer hardware at the time. As a result, many subsequent programming languages, including Python, adopted this convention.

While it may seem counterintuitive to start indexing at 0, there are several advantages to using zero-based indexing. For example, it makes it easier to calculate offsets and to perform array and list operations. It is also consistent with many other programming languages and has become a widely accepted convention.

That being said, some programming languages, such as MATLAB and R, use one-based indexing instead of zero-based indexing. This means that the first element of an array or list is indexed as 1, the second element as 2, and so on. It’s important to be aware of these differences when working with different programming languages to avoid confusion and errors.

Counting rows and columns in python

Why Can We Not Just Count the Rows and Columns Ourselves in Python?

While it is possible to count the rows and columns of a data structure in Python by manually iterating over the elements, there are several reasons why it may not be the most efficient or reliable method.

Firstly, if the data structure is very large or complex, manually counting the rows and columns can be time-consuming and error-prone. For example, if you have a two-dimensional array with thousands of rows and columns, manually iterating over each element to count the rows and columns can be a slow and inefficient process.

Secondly, Python provides built-in functions and libraries that are specifically designed for handling and manipulating data structures. Using these functions and libraries can often provide more accurate and efficient ways of counting rows and columns.

For example, if you are working with a two-dimensional array, you can use the NumPy library to count the rows and columns using the shape attribute. This is a built-in method that returns a tuple with the number of rows and columns in the array.

Similarly, if you are working with a pandas DataFrame, you can use the shape attribute to get the number of rows and columns in the DataFrame.

Overall, while it is possible to manually count the rows and columns of a data structure in Python, it is often more efficient and reliable to use built-in functions and libraries designed for handling data structures.

Also, in python, underscore (_) is used to separate strings because python cannot read space as a separator.

Data Preparation

To analyze data, a Data Scientist needs to perform the tasks of extracting the data, as well as cleaning and enriching it to make it useful.

Pandas is a popular open-source Python library that is widely used for data analysis and manipulation. One of its primary functionalities is the ability to extract and read data from various sources.

To extract data with Pandas, you can use functions like read_csv(), read_excel(), read_sql(), read_json(), and many others, depending on the format of the data. These functions allow you to read data from a variety of sources such as local or remote files, databases, web APIs, and more.

Once you have extracted the data, it is stored in a pandas DataFrame object. This object represents a tabular, spreadsheet-like data structure with rows and columns. You can perform various operations on this object, such as filtering, grouping, aggregating, and visualizing the data.

To clean and preprocess the data, you can use various methods provided by Pandas, such as dropna() to remove missing values, fillna() to fill missing values, replace() to replace values, and apply() to apply a function to each element of the DataFrame.

In general, Pandas is a powerful tool for data extraction and manipulation, and it provides a wide range of functionalities for working with data in Python.

Data Cleaning

Data cleaning, also known as data cleansing or data scrubbing, is the process of identifying and correcting or removing errors, inconsistencies, and inaccuracies from a dataset.

Data cleaning is a critical step in the data analysis process because it ensures that the data is accurate, complete, and consistent, which is necessary to obtain reliable insights and make data-driven decisions.

Some common examples of data-cleaning tasks include:

  • Removing duplicates: Identifying and removing records that appear multiple times in a dataset.
  • Handling missing values: Dealing with records that have missing or null values by imputing them with a value or removing them entirely.
  • Correcting inconsistent values: Ensuring that values within a dataset are consistent and standardized across the dataset.
  • Removing irrelevant data: Identifying and removing columns or records that are not needed for the analysis.

Data cleaning can be a time-consuming and complex process, depending on the size and complexity of the dataset. However, it is an essential step in ensuring the quality and reliability of the data used for analysis.

Data Visualization

Data visualization is an essential tool in data science. It allows data scientists to explore and communicate complex data in a way that is easy to understand and interpret. By using different types of data visualizations and the tools and techniques available, data scientists can gain insights into their data and effectively communicate their findings to stakeholders. As such, data visualization is a crucial aspect of any data science project.

Tools and Techniques for Creating Effective Data Visualizations

There are many tools and techniques used to create effective data visualizations. Some common tools and techniques include:

  1. Python Visualization Libraries: Python has many powerful visualization libraries, such as Matplotlib, Seaborn, and Plotly, which allow data scientists to create a wide range of visualizations.
  2. Dashboarding Tools: Dashboarding tools, such as Tableau and PowerBI, enable data scientists to create interactive dashboards that allow stakeholders to explore and interact with data.
  3. Color Theory: Color theory is an important consideration when creating data visualizations. Effective use of color can help to draw attention to important data points and to create a clear and visually appealing visualization.
  4. Design Principles: Effective data visualization also requires an understanding of design principles, such as balance, proportion, and hierarchy. By using these principles, data scientists can create clear and visually appealing visualizations that effectively communicate their findings.

Python serves as an important tool in Machine Learning and Data Science

Python is a popular programming language for machine learning and data science due to its ease of use, flexibility, and availability of a wide range of machine learning libraries. These libraries provide a collection of pre-built functions and algorithms that can be used to develop, test, and deploy machine learning models. In this article, we will discuss some of the most popular machine-learning libraries in Python.

  1. Scikit-learn: Scikit-learn is a widely used machine learning library that provides a range of supervised and unsupervised learning algorithms, including linear regression, support vector machines, decision trees, random forests, and clustering algorithms. It also includes functions for data preprocessing, model selection, and evaluation.
  2. TensorFlow: TensorFlow is a popular machine learning library developed by Google. It is primarily used for deep learning, which involves training neural networks to recognize patterns in data. TensorFlow includes a wide range of neural network architectures and is particularly well-suited for tasks such as image and speech recognition.
  3. Keras: Keras is a high-level deep learning library built on top of TensorFlow. It provides a user-friendly interface for building and training deep neural networks, and it supports a wide range of neural network architectures, including convolutional and recurrent neural networks.
  4. PyTorch: PyTorch is an open-source machine learning library developed by Facebook. Like TensorFlow, it is primarily used for deep learning and includes a range of neural network architectures. PyTorch is known for its flexibility and ease of use, and it is particularly popular in the research community.
  5. Theano: Theano is a popular machine-learning library that is primarily used for deep learning. It is known for its ability to optimize mathematical expressions and can be used to build and train a wide range of neural network architectures.
  6. XGBoost: XGBoost is a popular library for gradient boosting, a machine-learning technique that involves combining weak predictors to create a strong predictor. It is widely used in applications such as credit risk modeling, anomaly detection, and customer churn prediction.
  7. Pandas: While not strictly a machine learning library, Pandas is a popular data manipulation library that is widely used in machine learning projects. It provides a range of functions for reading, cleaning, and transforming data, making it an essential tool for data preparation and feature engineering.

These are just a few of the many machine-learning libraries available in Python. Each library has its strengths and weaknesses, and the choice of the library will depend on the specific requirements of the project. However, by leveraging the power of these libraries, data scientists can quickly develop and deploy machine learning models that can help to extract insights and drive business value.

What is Exploratory Data Analysis?

Exploratory data analysis (EDA)

Exploratory Data Analysis is also known as EDA. It is a process of analyzing and summarizing data in order to gain an understanding of its main characteristics.

Importance of EDA

The main purpose of EDA is to uncover patterns, trends, relationships, and anomalies in the data, and to identify important features and relationships that might be hidden in the data.

EDA involves a number of techniques, including data visualization, statistical analysis, and machine learning methods. Data visualization is a particularly important technique in EDA, as it allows analysts to visually explore the data and identify patterns and relationships that might not be immediately obvious from raw data.

The goal of EDA is to gain a deeper understanding of the data and to identify any potential issues or anomalies that may need to be addressed before further analysis or modeling can be done. EDA can be applied to a wide range of data, including both numerical and categorical data, and can be useful in a variety of fields, such as business, finance, healthcare, and social sciences.

Data Analysis & Data Modeling

Data analysis and data modeling are both essential aspects of data science. Data analysis refers to the process of examining and interpreting data to uncover patterns, trends, and insights that can inform decision-making or lead to further investigation. Data modeling, on the other hand, refers to the process of creating mathematical or computational models to represent and understand complex systems and phenomena.

There is a close relationship between data analysis and data modeling. In many cases, data analysis involves using statistical or machine-learning techniques to create models that can make predictions or generate insights based on observed data. These models may be simple, such as linear regression models, or more complex, such as deep neural networks. In either case, the models are built to capture patterns in the data and make predictions or inferences based on those patterns.

Data modeling can also inform data analysis. When creating a model, data scientists may need to perform exploratory data analysis to understand the underlying patterns in the data and select appropriate features or variables to include in the model. Additionally, data modeling can be used to simulate the behavior of complex systems, allowing researchers to test different scenarios and make predictions about how the system will respond to changes in input parameters.

Overall, data analysis and data modeling are complementary processes that work together to help data scientists gain insights and make predictions based on complex data. By using a combination of analytical and modeling techniques, data scientists can uncover patterns and relationships in the data that might not be immediately apparent through traditional analysis techniques.

Overall, python is an essential tool for data scientists in order to make informed decisions for businesses and organizations.

Lymah
Lymah

Written by Lymah

Software Engieneer || Technical Writer || Open Source Contributor ||