Cleaning data
correcting, selecting, converting, renaming
​Cleaning typo's
Suppose we want to sum the data in a column. We could use a sum, but we get a type error, since '53,2' is a string. In this case, we cannot simply transfer the data to a float. We need first to set the column as a string type, replace the ',' by a '.' (by a regex) and then transfer the column to float type
Convert values
Sometimes we do not want to use the 0 or 1 for a category but more meaningful values. This is especially handy in the graphical analysis. With the method map()
we can change values easily
Mind you that it is very pythonic to sequence the commands
Convert units
Pandas builts upon Numpy and the pandas DataFrames can deal with vectorized manipulations. The regex replace example above is an example of a vectorized manipulation. In the same way, we can convert the values of an entire column or DataFrame.
Rename columns
Data columns should describe as best as possible the content of the columns. For that purpose, we can rename columns by means of a dictionary
Drop rows or columns
Sometimes we want to drop columns because they are considered useless for the analysis. Often these columns are indexes or IDs. Maybe we want to drop the column because there is too much data missing or of poor quality.
Select/slice by value or by index
The df[df['columnname'] == condition]]
construct is to select all the records containing all the columns with that condition and not only the column name column.
Cleaning data example
In the example below all comes together. We have to read the data, deal with changing units, NaNs and useless information. The file we consider is the Energy Indicators file.
​
In the example above we can see that data of the file 'Energy indicators' need to be cleaned. The first two columns do not have added value, they can be removed. The column labels need to be replaced. The first 15 rows are headers basically, we can skip these. The Energy Supply
column is converted to gigajoules (there are 1,000,000 gigajoules in a petajoule). For all countries which have missing data (e.g. data with "...") we need to fill that with np.NaN
values. Lastly, some of the country names are renamed for merge purpose (source: University of Michigan)
Last updated
Was this helpful?