In this article, we will discuss how to convert a dataframe into a list of lists, by converting either each row or column into a list and create a python list of lists from them.

First of all, create a dataframe,

Contents of the dataframe object studentDfObj are,

## Convert a Dataframe into a list of lists – Rows Wise

In the above-created dataframe, we have to fetch each row as a list and create a list of these lists. Let’s do all that in a single line,

Output:

It converted the dataframe into a list of lists row-wise, i.e., each nested list contains a row of the dataframe. But what happened in a single line?

#### How did it work?

Let’s break the above single line into multiple lines to understand the concept behind it.

Step 1: Convert the Dataframe to a nested Numpy array using DataFrame.to_numpy() i.e.,

Output:

DataFrame.to_numpy()  converts a dataframe to a Numpy array. Therefore we got a 2D Numpy array here. We confirmed that by printing the type of the returned object.

Step 2: Convert 2D Numpy array into a list of lists

Numpy provides a function tolist(), which converts a Numpy Array into a list. Let’s call that function to the above created 2D Numpy array object,

Output:

It turned the 2D Numpy Array into a list of lists.

So, this is how we transformed a dataframe into a 2D Numpy Array and then into a List of Lists, where each nested list represents a row of the dataframe.

## Convert a Dataframe into a list of lists – Column Wise

Contents of the dataframe studentDfObj are,

Now to convert each column into a list and create a list of these lists,

Output:

#### How did it work?

It worked on the same concept we discussed above, just one additional step here i.e.

Step 1: Transpose the dataframe to convert rows as columns and columns as rows

Output

tansposedDFObj is a a transpose of the original dataframe i.e. rows in studentDfObj are columns in  tansposedDFObj and columns in studentDfObj are rows in tansposedDFObj.

Step 2: Convert the Dataframe to a nested Numpy array using DataFrame.to_numpy()

Output

Step 3: Convert 2D Numpy array into a list of lists.

Output

It converted the 2D Numpy Array into a list of lists. So, this is how we transformed a dataframe into a 2D Numpy Array and then into a List of Lists, where each nested list represents a column of the dataframe.

The Complete example is as follows,

Output:

### Design Patterns Resources

If you didn't find what you were looking, then do suggest us in the comments below. We will be more than happy to add that.