Convert Pandas Dataframe Column to List

Use Series.values.tolist() Method

To convert pandas dataframe column to list:

  • Use pd.DataFrame() to read position_salaries as a pandas data frame.
  • Use df["Position"] to get the column position from df
  • Use position.values to get values of the position
  • Use position_values.tolist() to get list of position_values as position_list

The code above will print the following output on the console:

Suppose we already have a Python library called pandas installed for working with data frames. If we don’t have it, we can install it using pip install pandas.

We imported the Python library pandas as pd.

pd.DataFrame() is a class of Python two-dimensional data structures used for data analysis and manipulation. We used it to read positon_salaries and to store the data frame in df.

In the pandas data frame, we can get columns of the data frame using the data retrieval technique that we use when working with arrays. The df["Position"] took the column name and stored the column in position.

In the Series.values function:

  • Series() is an n-dimensional array that holds data of any type. You may have questions about where this Series is in the code. Here the position is a Series created using df["Position"].
  • Series.values reads the Series and returns an object of type numpy.ndarray.

Once we got a series called position, we used position.values to get position_values.

tolist() is a predefined method in Python that does not hold any parameter. When we apply it to any iterable object, it converts that object to a list. We used it on our numpy.ndarray type position_values to get position_list.

Use list() Method

To convert the pandas data frame column to list:

  • Use pd.DataFrame() to read position_salaries as a pandas data frame.
  • Use df["Position"] to get the column position from df
  • Use position.values to get values of the position
  • Use list() to convert position_values to position_list

The code above will print the following output on the console:

We covered pd.DataFrame(), position, position_values, and Series while explaining the code using the Series.values.tolist() method.

In this code snippet, we used the list() method that takes an iterable object as an argument and creates an immutable list of that object. We passed position_values as an iterable Series to convert it to position_list.

Conclusion

You can use tolist() or list() methods to convert the pandas dataframe column to list.

You should always prefer tolist() over list() as tolist() is much faster than list() method.

That’s all about how to convert pandas dataframe column to list.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *