You've heard the cliché before: it is often cited that roughly %80~ of a data scientist's role is dedicated to cleaning data sets. I Personally haven't looked in to the papers or clinical trials which prove this number (that was a joke), but the idea holds true: in the data profession, we find ourselves doing away with blatantly corrupt or useless data. The simplistic approach is to discard such data entirely, thus here we are.
What constitutes 'filthy' data is project-specific, and at times borderline subjective. Occasionally, the offenders are more obvious: these might include chunks of data which are empty, poorly formatted, or simply irrelevant. While 'bad' data can occasionally be fixed or salvaged via transforms, in many cases it's best to do away with rows entirely to ensure that only the fittest survive.
Drop Empty Rows or Columns
If you're looking to drop rows (or columns) containing empty data, you're in luck: Pandas' dropna()
method is specifically for this.
Using dropna()
is a simple one-liner which accepts a number of useful arguments:
Technically you could run df.dropna()
without any parameters, and this would default to dropping all rows where are completely empty. If thats all you needed, well, I guess you're done already. Otherwise, here are the parameters you can include:
- Axis: Specifies to drop by row or column.
0
means row,1
means column. - How: Accepts one of two possible values: any or all. This will either drop an axis which is completely empty (all), or an axis with even just a single empty cell (any).
- Thresh: Here's an interesting one: thresh accepts an integer, and will drop an axis only if that number threshold of empty cells is breached.
- Subset: Accepts an array of which axis' to consider, as opposed to considering all by default.
- Inplace: If you haven't come across
inplace
yet, learn this now: changes will NOT be made to the DataFrame you're touching unless this is set toTrue
. It'sFalse
by default.
Pandas' .drop() Method
The Pandas .drop()
method is used to remove rows or columns. For both of these entities, we have two options for specifying what is to be removed:
- Labels: This removes an entire row or column based on its "label", which translates to column name for columns, or a named index for rows (if one exists)
- Position: Passing an array of integers to
drop()
will remove rows or columns by their default position in table. Passing an array[0, 1]
todrop()
would either drop the first two rows of a table, or the first two columns, depending on the axis we specify.
To better illustrate this, let's look at the possible arguments drop()
accepts:
- Labels: Accepts either an array of strings (ie:
labels=['column_1', 'column_2']
) or an array of integers (ie:labels=[0, 1]
). Passed an array of strings will drop based on column name/row index, whereas an array of integers will drop based on position. - Axis: Specifies whether we're dropping rows or columns. A value of
0
denotes row index, where a value of1
specifies column name. - Index: This is shorthand way of dropping rows by index name. Passing a single array of strings to
index
is effectively the same as passing the same array tolabels
and passing anaxis
of0
. - Columns: Shorthand for accomplishing the reverse of
index
. Passing a single array of strings tocolumns
is effectively the same as passing the same array tolabels
and passing anaxis
of1
. - Levels: Used in sets of data which contain multiple hierarchical indexes (this likely doesn't concern you).
- Inplace: As always, methods performed on DataFrames are not committed unless explicitly stated. The purpose of this is to presumably preserve the original set of data during ad hoc manipulation.This adheres to the Python style-guide which states that actions should not be performed on live sets of data unless explicitly stated. Here is a video of some guy describing this for some reason.
- Errors: Accepts either ignore or raise, with 'raise' set as default. When errors='ignore' is set, no errors will be thrown and existing labels are dropped.
Dropping Columns
Let's say we have a DataFrame which contains a column we've deemed useless. To removing a column named preferred_icecream_flavor from our DataFrame looks like this:
Alternatively:
If we wanted to drop columns based on the order in which they're arranged (for some reason), we can achieve this as so
Dropping Rows
The row equivalent of drop()
looks similar. Let's drop a rows where our DataFrame has been index with first names, like Todd and Kyle:
Or of course:
Drop Duplicates
It's common to run into datasets which contain duplicate rows, either as a result of dirty data or some preliminary work on the dataset. Pandas has a method specifically for purging these rows called drop_duplicates()
.
When we run drop_duplicates()
on a DataFrame without passing any arguments, Pandas will refer to dropping rows where all data across columns is exactly the same. Running this will keep one instance of the duplicated row, and remove all those after:
drop_duplicates()
has a few options we can play with:
- Subset: Let's say we wanted to detect duplicates only in a certain row, or even number of rows. We can pass either a column name (string) or a collection of columns (list) via the subset attribute to perform duplicate checking only against the provided columns. Note: even though we're only using certain columns to determine duplicates, any detected duplicates will drop the entire row.
- Keep: If we find duplicates, how do we know which of the duplicates to keep? By default, Pandas will keep the first appearance of that row, and discard all others thereafter (
keep='first'
). To keep the last, we would usekeep='last
. If we just want to drop all duplicates, we usekeep=False
. - Inplace: Using
df.drop_duplicates(inplace=True)
is the same as our example above:df = df.drop_duplicates()
Drop by Criteria
We can also remove rows or columns based on whichever criteria your little heart desires. For example, if you really hate people named Chad, you can drop all rows in your Customer database who have the name Chad. Screw Chad.
Unlike previous methods, the popular way of handling this is simply by saving your DataFrame over itself give a passed value. Here's how we'd get rid of Chad:
The syntax may seem a bit off-putting to newcomers (note the repetition of df
3 times). The format of df[CONDITION]
simply returns a modified version of df
, where only the data matching the given condition is affected.
Since we're purging this data altogether, stating df = df[CONDITION]
is an easy (albeit destructive) method for shedding data and moving on with our lives.