Pandas is a data manipulation and analysis library for python. It is heavily used by the Machine Learning community to clean, transform, and analyze structured data.
Why should you read this post?
I’ve been using pandas for working with structured data like Electronic Health Records (EHR), insurance claims, sensory data from wearables, etc. Pandas is a powerful data manipulation library that I’ve been consistently under-utilizing. In this post, I describe a list of pandas functions that I wish I knew about when I started with Data Science. If you are someone who works with data for a living you might find this useful.
Select features from file
Sometimes csv files contain too much information. Too many irrelevant columns. I used to read the whole file into memory and then get rid of the irrelevant columns. Instead, we could read only the useful columns from the file.
Consider the example of Melbourne housing prices data. Say we are interested in the following features:
read_csv allows us to specify which columns we are interested in.
Parse Date as datetime data type
pandas by default parses columns containing date as the generic “object” type.
We could take control of how it is parsed by using the
parse_date option in
Dealing with Missing values
You may have noticed several NaN (missing) values in the data frame.
We can decide to remove the rows with missing data or fill them in depending on the situation.
There are many ways to fill in the missing values.
We could fill in with average (mean, median) or most likely values (mode).
Or we could use the values from the neighboring rows.
bfill fills in using the value from the next rows.
ffill fills in using the value from the previous rows.
Almost every time I perform data analysis, I use conditions to filter out rows. Often I end up having to use multiple conditions leading to long, awkward lines of code.
Alternatively, we could use
df.query and enter our conditions as a string.
Is it in my list?
Here is another one that I use a lot. Let us say we are interested in a limited list of suburbs. How do we filter out the rest of the suburbs?
pandas offers string-specific functionalities using a
There are methods equivalent to python’s string manipulation methods like lower, upper, strip, isalpha, find, index, split, and regex-based functions like match, search, and extractall (equivalent to
You can find a lit of string methods supported by pandas here.
pandas allows you to work with Date type objects using the
pandas.Series.dt can be used to access date, hour, day, month, year, etc, from a Datetime object.
It also supports many operations on Datetime objects like
Group and Summarize
Groupby splits the data into different groups given a column. Using multiple columns to group will create a hierarchy of groups. The example below groups the data by “Regionname” and “Suburb” and summarizes the “Landsize” values within these groups.
Ranking and Sorting
During data analysis, we’ll be interested in ranking entries in the data frame based on a variable of our choice. Looking at the extremes in the housing market might reveal interesting patterns. In the example below, we rank the housing entries based on their market price.
Instead, we could just sort the entries based on one or more columns.
pandas has a handy function to calculate pair-wise correlation between variables. The correlation matrix is a good indicator of which features are useful (strong correlation with target variable) and which features are correlated with each other.
When working with data from multiple sources, there is a need to combine them after cleaning and transformation. Pandas has functions to merge, join, append and concat data. merge and join are different ways of doing the same thing. merge performs a database-style join on data frames. concat and append perform concatenation of data frames along a particular axis.
In the code below,
reset_index removes “Regionname” and “Suburb” as indices.
Now to perform merge we need to explicitly include column names.
The merge operation removes the indexes from the resulting data frame.
Doing a merge on two unindexed data frames gives the same result.
We can do sql-like merges using left, right, inner and outer methods.
indicator=True lets us know how each row was merged.
Concatenation is a simpler operation that combines two or more data frames row-wise or column-wise.
Concatenation work along the column axis using
pd.crosstab takes an index and a list of columns as inputs and creates a simple cross tabulation between two or more factors.
It creates a frequency table of factors.
The frequency can be replaced by a different kind of summary by specifying a summarization function.
Multi-level data frames
It might be useful to group our entries based on, say the source of the data if we are acquiring and integrating data from different sources. Grouping like that creates a multi-level data frame.
pandas_profiling is an external package that generates a detailed report on a pandas data frame. It generates a html report which includes tons of useful information such as global data statistics, variable statistics, missing value count, interaction between variables, correlation between variables, etc.
pandas is an incredibly powerful, flexible, and intuitive tool for working with structured data.
I’m thinking of writing a follow-up blog that covers SQL-like functions in pandas and compares SQL queries with pandas functions.
That’s it for now. I hope one of these tricks helps you improve your workflow. See you soon with more.
If you got something to say leave a comment below.