# How to do Descriptive Statistics in Python using Numpy

In this short post we are going to revisit the topic on how to carry out summary/descriptive statistics in Python. In the previous post, I used Pandas (but also SciPy and Numpy, see Descriptive Statistics Using Python) but now we are only going to use Numpy. The descriptive statistics we are going to calculate are the central tendency (in this case only the mean),  standard deviation, percentiles (25 and 75), min, and max.

In this example I am going to use the Toothgrowth dataset (download here). It is pretty easy to load a CSV file using the genfromtxt method:

Notice the arguments we pass. The first row has the names and that is why we set the argument ‘names’ to True. One of the columns, further, has strings. Setting ‘dtype‘ to None enables us to load both floats and integers into our data.

## Descriptive statistics using Numpy

In the next code chunk, below, we are going to loop through each level of the two factors (i.e., ‘supp’, and ‘dose’) and create a subset of the data for each crossed level.

If you are familiar with Pandas, you may notice that subsetting a Numpy ndarray is pretty simple (data[data[yourvar] == level). The summary statistics are then appended into a list.

## The results

From the list of data we are going to create a Numpy array. The reason for doing this is that it will get us a bit prettier output. Especially, when we are setting the print options (line 19, below).

That was it. I still prefer doing my descriptives statistics using Pandas. Primarily, because of that the output is much more nicer but it’s also easier to work with Pandas dataframes compared to Numpy arrays.

This site uses Akismet to reduce spam. Learn how your comment data is processed.