How do you import data into Python?

Python is increasingly growing in popularity thanks to the large number of packages that cater to the need of the data scientist. Importing data into Python thus becomes the starting point for any data science project that you will undertake. This guide gives you a comprehensive introduction into the world of importing data into Python.

There are number of file formats that are avaliable that offer you with a source of structured and unstructured data.

The various sources of structured data are:

  • .CSV files
  • .TXT files
  • Excel files
  • SAS and STATA files
  • HDF5 files
  • Matlab files

The various sources of unstructured data are

  • Data from the web in the form of HTML pages

This guide will teach you the fundamentals of importing data from all these sources straight into your python workspace of choice with minimal effort. So let’s get coding!

1) CSV files

CSV files usually contain mixed data types and it’s best to import the same as a data frame using the pandas package in python. You can do this with the code snippet shown below:

We first import the pandas package and then store the file of interest into a variable called ‘filename’. We then use the function pd.read_csv() in order to read the filename into Python and we save the same into the variable ‘data’. The data.head() function is used to display the first 5 rows along with the column names of the dataset.

2) TXT files

The next type of file that we might encounter on our quest to becoming a master data scientist is the .TXT file. Importing these files into python is as easy as importing the CSV file and can be done with the code snippet shown below:

The above line of code that uses the ‘with’ is called as the context manager in python. The open() function opens the file – ‘file.txt’ as a read only document using the argument ‘r’. We then read the file using the argument and printing out the same. If you want to edit the .txt file that you just imported you would want to use the ‘w’ argument with the open() function instead of the ‘r’ argument.

3) Excel Files

Excel files are a huge part of any business operation and it becomes imperative that you learn exactly how to import these into python for data analysis as a pro data scientist. In order to do this we can use the code snippet shown below:

In the above code we first imported pandas. We then stored in the excel file into a variable called ‘file’ after which we imported the file into python using the pd.ExcelFile() function. Using the ‘.sheet_names) we printed out the sheet names present in the excel file. We then extracted the contents of the first sheet as a dataframe using the ‘.parse()’ function.

4) SAS and STATA files

Statistical analytic software is widespread in the business analytics space and needs to be given due diligence. Let’s take a close look at how can get them into python for further analysis.

Importing SAS files requires the SAS7BDAT package while importing STATA files requires only the pandas package.

5) HDF5

The HDF5 file format stands for  Hierarchal  Data Format version 5. The HDF5 is very popular for storing large quantities of numerical data which can span from a few Gigs to exabytes. It’s very popular in the scientific community for storing experimental data. Fortunately for us we can import these files quite easily into python by using the code snippet shown below:

In the above code snippet the package that we are using to import the hdf5 file is the h5py package. The function h5py.file() can be used to import the file in both read only ‘r’ and write ‘w’ modes.

6) Matlab files

Matlab files are used quite extensively by electronic and computer engineers for designing various electrical and electronic systems. Matlab is built around linear algebra and can store a lot of numerical data that we could use for analysis.  In order to import a matlab file we can use the code snippet illustrated below:

Matlab files can be imported using the package and the function that comes along with the package. When we import matlab files into python we import it as a dictionary containing key:value pairs of your data from matlab.

7) Data from the web

Data from the web is usually in the form of unstructured data that has no order to linearity to it. However, we can find structured data on some websites like Kaggle and the UCI machine learning repository. Such files can be downloaded directly into python from the web using the code snippet below:’

In the code above we have used the urlretrieve package from urllib.request in order to download a csv file from my website. We then saved it as a dataframe locally using the pandas package.

In order to import HTML pages into python we can make use of the ‘requests’ package and a couple of lines of code that’s shown below:

The requests.get() function sends a request to the server to import the webpage while the file.text will convert the webpage into a text file.

Most of the time data from webpages don’t really make a lot of sense. It’s usually in the form of jumbled up text and a lot of code that does not resonate well with anybody. In order to make sense of the data that we import from the web we have to make use of the BeautifulSoup package that is offered by Python.

The .prettify() function displays useful information about your HTML file in a structured fashion while the .title() function would give you the title of your HTML page. For more information about the various functions and the in-depth documentation of the BeautifulSoup package please visit the link:

Now that you have pretty good idea about how you can import data into python you can finally start your next big Hackathon/Kaggle competition! Be sure to keep exploring the various ways you can explore all kinds of data and all the packages available in the python documentation pages found on the web. There’s no end to the knowledge you can acquire.

Happy coding!




Building an end to end predictive analytics project in 5 easy steps!

If you’re new to the world of data science and analytics and you have some basic knowledge in statistics and R/Python but you’re not sure how you can get started on your first big project that you can add to your portfolio – then this is the guide for you!

In this guide I will cover how you can dig into a dataset and uncover insights using various visualization techniques along with building your machine learning model and validating the same. I will primarily be using R to illustrate a couple of examples but the approach that you need to take are language independent.

So what are these 5 steps?

STEP 1: Importing, Cleaning, Manipulating and Visualizing your Data

STEP 2: Building your machine learning model

STEP 3: Feature Selection

STEP 4: Applying Transformations to your model

STEP 5: Validating your model

Now that you have a brief idea about the steps involved in your project let’s get started!

Before we can actually dig into a dataset we need a dataset. There are a plethora of datasets available online from multiple sources – Some complex, Some Simple and some are just beyond comprehension for the new data scientist. Below are a list of a few datasets that you can download for free that I think are great for someone who has just entered the world of data.

  1. Human Resource Analytics (Kaggle) – 
  2. Credit Card Fraud Detection (Kaggle) –
  3. Iris Species (UCI Machine Learning) –
  4. World University Ranking (Kaggle) –

These 4 datasets are a great starting point because most of them are quite clean and not very messy, contains fewer text elements and mostly numeric factors. When choosing a dataset to work on it’s important that you pick a topic that you are genuinely interested/passionate about because that fosters a curiosity that will lead you to discover the hidden insights from the dataset that are usually as valuable as gold!

STEP 1: Importing, Cleaning, Manipulating and Visualizing your data

Once you have downloaded these files from the respective websites, the first step is to import the data into RStudio or into your Python Workstation of choice.

For R you need to download R and RStudio

Download Link for R:  MAC:


Download Link for RStudio:

For Python users you are going to need

Download Link for Python:

Now for the studio that you are going to be using for Python Depends on you but I would recommend Rodeo because it’s very similar to RStudio and it’s perfect for Data Analytics and Predictive Modeling

Download Link for Rodeo:

Once you’ve downloaded the required software and follow it’s easy step by step installation procedure your workstation would look something like this: 

The top left corner contains the editor where you will be writing your code while the bottom left is your console where you can execute commands line by line. The top right corner will contain information about your datasets and the bottom right corner will contain information about the packages that you have loaded and the plots that you visualize.

Next we want to import a dataset. There are multiple ways to import a dataset into RStudio and Rodeo using R and Python Respectively and you will want to use different techniques to import different types of datasets like CSV, Excel and the like. Below is an example of importing a CSV File into RStudio

Once we have the dataset the next thing we want to do is clean it for any obvious faults that it may have. Some of the most common faults in any dataset are:

  • Invalid Column names
  • Two types of data under one column
  • Row data stored as column variables
  • Column names stored as row data
  • Single observational unit (Ex: Data related to people only) stored in two data different data frames
  • Multiple observational units ( Ex: Data related to people and aliens) stored in the same data frame.

Below I have identified that my column names are invalid and I proceed to clean it using the code shown below:

Next you want to use the dplyr package in R to manipulate your dataset to get valuable insights from the dataset under study. If you’re a python user you would want to work with the pandas package. Drawing insights using the two packages mentioned above will give you an idea about the key aspects about your data such as what factors actually have an influence on your variable of interest. They also give you an idea about what you need to visualize. Manipulating data using these tools are a course in itself and would probably require another blog post in detail. So let’s get onto the next step.

Once you know what to look for thanks to your awesome manipulation skills we proceed to data visualization. For some, this is the most lucrative part about being a data scientist and for good reason – you portray yourself as an artist at this stage.

In R you would want to go for the Ggplot package while in python you would want to pick the Matplotlib package. Below is an example of a visualization that I had run to figure out who would default on a loan based on his/her account balance


The 0 indicates that the person has not defaulted while the 1 indicates that a person has defaulted on their loan. The count indicates the number of people that are inclusive in each category. This kind of visualization is vital in any predictive modeling project.

STEP 2:  Building your machine learning model!

This step requires a clear understanding about how the various kinds of machine learning models work so that you can make an informed choice about which model that you need to pick for the given problem. There are a large number of machine learning algorithms out there such as regression, logistic regressions, random forests and the like.

For a person setting his/her foot into the world of data you would want to use the Caret package in R as it’s very simple to implement. The sci-kit learn is what you would want to use if you’re a python user. Below is a snippet of the code that I’ve used to build a logistic regression model using the caret package in R.


STEP 3: Feature Selection

Feature Selection is an important element in any predictive analytics project as you want to determine the features that affect the  decision variable the most! If you have 20+ factors that contribute/affect your decision variable you would want to reduce that to 10 or 8 key variables and build your model around that. Below is the Recursive Feature Elimination that I have applied using the caret package in R to select the features that affect my decision variable the most:

STEP 4: Applying Transforms to your model

There are a multitude of transformations out there. Transformations fundamentally change a certain aspect of your dataset to give you a better prediction and a better fitting model. Sometimes transformations can lead to you overfitting your model which is something you must avoid. Transformations can be applied on a trial and error basis and you can see the results by comparing how your model’s accuracy improves.

Below is a quick summary of all of the transform methods supported in the method argument of the preProcess() function in caret.

  • BoxCox“: apply a Box–Cox transform, values must be non-zero and positive.
  • YeoJohnson“: apply a Yeo-Johnson transform, like a BoxCox, but values can be negative.
  • expoTrans“: apply a power transform like BoxCox and YeoJohnson.
  • zv“: remove attributes with a zero variance (all the same value).
  • nzv“: remove attributes with a near zero variance (close to the same value).
  • center“: subtract mean from values.
  • scale“: divide values by standard deviation.
  • range“: normalize values.
  • pca“: transform data to the principal components.
  • ica“: transform data to the independent components.
  • spatialSign“: project data onto a unit circle.


STEP 5: Validating your model

Once you’ve built a couple of models using different machine learning algorithms, or you’ve built models with the same algorithms but with different transformations you will want to compare all your models and see which model works the best for your given problem.  Fortunately for us we have a metric that lets us do just this and it’s called ROC (Reciever Operating Characteristic). Models having the higher average ROC are better. Below is a snippet of how I have used the caretEnsemble package to compare the ROC between two models:

We can clearly see how model 2 is better than model 1 because it has a higher average ROC indicated by the black dot along with a lower variance in it’s data.

That’s it!

If you’ve come this far into this guide I’m sure you can get started with your very first predictive analytics project which you can showcase as your portfolio. I hope this guide helps anyone who’s passionate about breaking into the world of data get their first project out for the world to see.

Be sure to conclude the results of your work and always use LaTex or R markdown to report your work for potential employers to see.

Using GitHub to publish the code that you have used is also another way to gain the interest of employers.

Happy Coding!

How do you choose the right laptop for Data Science?

Data Analysis, Machine Learning model training and the like require some serious processing power. If you’re someone who’s just entered the world of data or if you’re a veteran data scientist that needs an upgrade on his/her local machine this post will provide you with the comprehensive guide that is necessary to make the right choice when it comes to buying a machine that is capable of handling your data-sets.

When it coms to choosing the right machine you usually have to choose between two factors:

  1. Portability
  2. Processing Power

The higher the processing power the heavier the laptop gets and hence it’s portability is reduced and vice versa. The next thing to note is that with higher power the battery life also shrinks and as a result you are losing out on portability yet again. Huge datasets these days have outgrown the processing power of a single machine and will depend on you accessing the cloud for processing, in which case portability is going to be of value to you.

With that said, let’s identify the minimum requirements that you would require when it comes to a laptop worthy of being called a data scientist’s weapon of choice.


The minimum ram that you would require on your machine would be 8 GB. However 16 GB of RAM is recommended for faster processing of neural networks and other heavy machine learning algorithms as it would significantly speed up the computation time. Personally, 8 gigs of RAM works just fine if you build your algorithms very efficiently and you can put your machine on sleep mode while it takes its times to compute.


I cannot stress upon the importance of an NVIDIA GPU when it comes to choosing your machine. This is because most deep learning libraries (Theano, Torch, Tensorflow) use the CUDA processor which compiles only on NVIDIA processors. If you want to use a machine that is powered by an AMD or Intel HD GPU you need to be prepared to write a lot of low level code in OpenCL. With that being said, you can opt for the NVIDA 960 series and above.


Once you have the RAM and GPU in check, the processor should come right along with the machine you are selecting. However for the purpose of this guide, the intel i5, 7th generation would be the minimum requirement while the i7, 7th generation would be the ideal recommendation.


SSDs make your machine incredibly fast. However, getting a machine with a good amount of SSD would burn a hole in your wallet. Keeping this in mind, 1 TB of Hard Disk would be the minimum requirement as data sets tend to only get bigger by the day. If you’re opting to go for a machine with an SSD, ensure that there is 256 GB of SSD storage available on the machine. You might have to purchase an external HD in the case of the latter.

With the minimum requirements out of the way let’s find out what the best laptops are in today’s market both in terms of portability and processing power


As a developer you always want to go with linux. Luckily most systems with a MAC or Windows build can run the linux as either a virtual machine or on startup using software like BootCamp for the mac. Additionally parallels is a software that you can use to run two operating systems side by side on your machine.




Apple MacBook Pro – £1399/$1429/INR 139,000


The MacBook pro is an incredible device for data analysis that is light and has an exceptionally good battery life of 7 hours. The Mac comes with a 2.5 Ghz quad core intel i7 processor, along with 16 gigs of RAM and an NVIDIA 760 M GPU. It has a beautiful 15 inch display as well. The device comes well equipped with a 512 GB of hard disk.

Link to buy the machine in the USA:

Link to buy the machine in the UK:

Link to buy the machine in India:


MSI gl62 – £849/$939/INR 108,002

The MSI is a pure beast when it comes to processing power because it comes with 16 gigs of RAM, NVIDIA 960M and the intel i7. Apart from these it also has 256 Gigs of SSD and a 1 TB HD. The only downside is that it’s relatively heavy to tug around weighing in at a little over 5.2 pounds. The battery life is not the greatest with only 4 hours of battery life when running normal applications. This reduces to 2 hours when you run data intensive applications and programs. This means that you will always require a power cord in hand. The build quality is good, however you are not going to the premium feel that comes with a MacBook. Overall, it’s a powerful machine.

Link to buy the machine in the US:

Link to buy the machine in the UK:

Link to buy the machine in India:


If you’re looking for a cheap machine or amazing portability + battery life but still want to run neural networks there’s a solution – work on the cloud. Amazon AWS EC 2 is a virtual machine that lets you run any operating system you want and modify it to your preference and requirement. You can set up a web based IDE for R (RStudio) which is essentially running on the server for another computer that is powerful enough to run your algorithms while you use your computer. All processing is done on Amazon’s servers. So all you need is an internet connection. Amazon AWS EC2 comes with a year of free trial after which you pay according to your RAM/processing power requirements.

The only downside is that it takes some time to learn how to set up and configure the AWS and you need an internet connection at all times to work on your datasets. Barring this, it’s an exceptional way to buy any system of your liking and configure it for the AWS.

With this regard, the MacBook Air is a excellent machine. Windows machines that are as low as 250-350$ can also be configured for the AWS.

In conclusion buying a machine for data science can be a daunting task but this guide should have made things easier for you and you now know what to look for. Below is an infographic that shows you the ideal specifications for a laptop that is built for data science based applications.