How to Create a Matrix from a Data Set in Seaborn with Python


In this article, we show how to create a matrix from a data set in seaborn with Python.

So many times, as convention, you load a data set in seaborn using the load_dataset() function.

Many times, these data sets have integer indexes.

However, when creating a plot such as a matrix plot, the data needs to be converted into a matrix before we can plot it.

Therefore, we need to do a matrix conversion.

We can do a matrix conversion using the pivot_table() function. With this function, we can specify which column we want to be the rows, which column we want to be the columns, and the the values of these data points.

In the following code below, we show load in the data set, flights, from seaborn. This data set is then converted into a matrix, in which the month column becomes the rows, the year column is the columns, and the passengers column are the values.

By convention, we import seaborn as sns.

In order to see the graph within the editor, we put in the statement, %matplotlib inline

You put this statement in if you are using an editor such as jupyter notebooks so that you can see the graph output in the editor.

Seaborn already has built-in data sets.

One data set that can be used is tips.

We import this dataset with the line, flights=sns.load_dataset('flights')

We then output the contents of tips using flights.head() You can see that the columns are year, month, and passenger.

We then convert this data set into a matrix using the line, flights.pivot_table(index='month', columns='year',values='passengers')

The month column becomes the rows. The year column becomes the columns. And the passengers column becomes the values.

After this function, you can now see this arrangement.

Again, this is an import conversion, because in order to plot matrix plots, the data needs to be in matrix format first.

And this is how to create a matrix from a data set in seaborn with Python.

Related Resources

How to Randomly Select From or Shuffle a List in Python

HTML Comment Box is loading comments...