Pandas series to python list

Convert pandas Series to List in Python

To convert a pandas Series to a list in Python, the easiest way by using values.tolist() on a pandas Series.

import pandas as pd df = pd.DataFrame() animal_types = df["animal_type"].values.tolist() print(animal_types) #Output: ['dog', 'cat', 'dog', 'cat', 'dog', 'dog', 'cat', 'cat', 'dog']

You can also use list() function to convert a pandas Series to a list.

import pandas as pd df = pd.DataFrame() animal_types = list(df["animal_type"]) print(animal_types) #Output: ['dog', 'cat', 'dog', 'cat', 'dog', 'dog', 'cat', 'cat', 'dog']

When working with collections of data, the ability to be able to easily access certain pieces of information is valuable.

One such situation is if you want to get the values of a pandas Series and create a list in Python.

Читайте также:  Модель изинга на питоне

There are a few ways you can convert the values of a pandas Series to a list.

Having values of a Series in a list can be useful if you want to loop over the values and perform an action.

The easiest way is to access the Series values with the pandas Series values attribute and then use the tolist() function.

Below shows a simple example of how you can convert a pandas Series to list in Python.

import pandas as pd df = pd.DataFrame() animal_types = df["animal_type"].values.tolist() print(animal_types) #Output: ['dog', 'cat', 'dog', 'cat', 'dog', 'dog', 'cat', 'cat', 'dog']

Using list() to Convert pandas Series to List in Python

Another way you can convert the pandas Series values to a list is with the Python list() function.

list() tries to convert a Python object to a list. The list representation of a pandas Series is the values of the Series.

Below shows another example of how you can get the Series values of a pandas Series as a list in Python.

import pandas as pd df = pd.DataFrame() animal_types = list(df["animal_type"]) print(animal_types) #Output: ['dog', 'cat', 'dog', 'cat', 'dog', 'dog', 'cat', 'cat', 'dog']

Hopefully this article has been useful for you to be able to learn how to convert pandas Series to a list in Python.

  • 1. Sort by Two Keys in Python
  • 2. Create Empty List in Python
  • 3. Check if File Exists in AWS S3 Bucket Using Python
  • 4. Python Print List – Printing Elements of List to the Console
  • 5. Sort Series in pandas with sort_values() Function
  • 6. Intersection of Two Lists in Python
  • 7. How to Add Commas to Numbers in Python
  • 8. Break Out of Function in Python with return Statement
  • 9. Python ljust Function – Left Justify String Variable
  • 10. How to Serialize a Model Object with a List of Lists Using Django Rest Framework in Python

About The Programming Expert

The Programming Expert is a compilation of a programmer’s findings in the world of software development, website creation, and automation of processes.

Programming allows us to create amazing applications which make our work more efficient, repeatable and accurate.

At the end of the day, we want to be able to just push a button and let the code do it’s magic.

You can read more about us on our about page.

Источник

Series.tolist() – Convert Pandas Series to List

Pandas Series.tolist() method is used to convert a Series to a list in Python. In case you need a Series object as a return type use series() function to easily convert the list, tuple, and dictionary into a Series. In this article, we can see how to convert the pandas series to a list, and also we can see how to convert the Pandas DataFrame column to a list with several examples.

1. Quick Examples to Convert Series to list

If you are in hurry below are some quick examples of how to convert series to list.

 # Below are some quick examples. # Example 1: Convert pandas Series to List data = s = pd.Series(data) listObj = s.tolist() # Example 2: Convert the Course column of the DataFrame to a list listObj = df['Courses'].tolist() # Example 3: Convert a pandas series to a list using type casting listObj = list(s) # Example 4: Convert a DataFrame column to a list using type casting listObj = list(df['Courses']) 

2. Syntax of Pandas.Series.tolist()

Following is the syntax of the Pandas.Series.tolist() .

 # Syntax of Series.tolist() Pandas.Series.tolist() 

It returns the list of values.

3. Create Series From Dictionary

pandas Series is a one-dimensional array that is capable of storing various data types (integer, string, float, python objects, etc.). In pandas Series, the row labels of the Series are called the index. The Series can have only one column. A List, NumPy Array, Dict can be turned into a Series.

The following example creates a Series from a Python dictionary using pd.Series() function.

 # Create a Dict from a input import pandas as pd data = s = pd.Series(data) print (s) 
 # Output: Courses pandas Fees 20000 Duration 30days dtype: object 

4. Usage of Pandas Series tolist()

In Python, pandas is the most efficient library for providing various functions to convert one data structure to another data structure. Series.tolist() is one of the functions to convert the structure of the data. Using this function we are able to convert Series to Python list easily. Let’s take an example.

 # Create a list from Series listObj = s.tolist() print("Our list:", listObj) # Output : # Our list: ['pandas', 20000, '30days'] 

5. Convert DataFrame Column (Series) to List

We consider that the columns of a pandas DataFrame are pandas Series objects hence, we can convert the columns of DataFrame into a list using the tolist() method. First, let’s create Pandas DataFrame from dictionary using panads.DataFrame() function and then use tolist() to convert one of the column (series) to list. For example,

 # Create Dict object courses = # Create DataFrame from dict df = pd.DataFrame.from_dict(courses) print(df) 
 # Output: Courses Fee Duration 0 Spark 20000 35days 1 PySpark 20000 35days 2 Java 15000 40days 3 pandas 20000 30days 

After creating DataFrame we have to pass one of its columns which, we want to convert to a list into this function, it returns the series as a list.

 # Convert the Course column of the DataFrame to a list listObj = df['Courses'].tolist() print("Our list:", listObj) print(type(listObj)) 
 # Output: Our list: ['Spark', 'PySpark', 'Java', 'PHP'] 

6. Use Type Casting Method Convert Series to List

Type casting is the process to convert one datatype to another datatype. Using type casting we can convert a series to a list in pandas directly. For that, we need to pass the series into the list() function.

 # Convert a pandas series to a list using type casting listObj = list(s) print('Our list:', listObj) # Output : # Our list: ['pandas', 20000, '30days'] 

We can also perform type casting to convert a DataFrame column to a list. For example.

 # Convert a DataFrame column to a list using type casting listObj = list(df['Courses']) print('Our list:', listObj) # Output : # Our list: ['Spark', 'PySpark', 'Java', 'PHP'] 

Conclusion

In this article, I have explained to convert pandas Series into a Python list by using Series.tolist() method and also explained converting data columns to list and also using type casting.

References

You may also like reading:

Источник

Convert Pandas Series to a List

Lists are very flexible to work with in python and it may happen depending upon the use-case that you’d want to work with a list instead of a series. In this tutorial, we will look at how to convert a pandas series to a list.

How to convert a pandas series to a list?

There are a number of ways to get a list from a pandas series. You can use the tolist() function associated with the pandas series or pass the series to the python built-in list() function. The following is the syntax to use the above functions:

📚 Discover Online Data Science Courses & Programs (Enroll for Free)

Introductory ⭐

Intermediate ⭐⭐⭐

🔎 Find Data Science Programs 👨‍💻 111,889 already enrolled

Disclaimer: Data Science Parichay is reader supported. When you purchase a course through a link on this site, we may earn a small commission at no additional cost to you. Earned commissions help support this website and its team of writers.

# using tolist() ls = s.tolist() # using list() ls = list(s)

Here, s is the pandas series you want to convert. Both the functions return a list with the series values.

Examples

Let’s look at some examples of using the above methods to create a list from a series. First, we’ll create a sample pandas series which we will be using throughout this tutorial.

import pandas as pd # pandas series Wimbledon winners from 2015 to 2019 wimbledon_winners = pd.Series(index=[2015, 2016, 2017, 2018, 2019], data=['Novak Djokovic', 'Andy Murray', 'Roger Federer', 'Novak Djokovic', 'Novak Djokovic'], name='Name') # display the series print(wimbledon_winners)
2015 Novak Djokovic 2016 Andy Murray 2017 Roger Federer 2018 Novak Djokovic 2019 Novak Djokovic Name: Name, dtype: object

You can see the contents of the series object above. Let’s confirm the type of the object.

# check the type print(type(wimbledon_winners))

We now have a pandas series containing the name of Wimbledon Winners from 2015 to 2019 with the year as its index.

1. Series to list using tolist()

First, let’s see the usage of the pandas series tolist() function to get a list from a series.

ls = wimbledon_winners.tolist() # check the type print(type(ls)) # print the content print(ls)
 ['Novak Djokovic', 'Andy Murray', 'Roger Federer', 'Novak Djokovic', 'Novak Djokovic']

You can see the resulting list with all the series values. Note that the tolist() function does not modify the series in-place rather it returns a list of the series values.

For more on the pandas series tolist() function, refer to its documentation.

2. Series to list using list()

Alternatively, you can use the python built-in list() function to create a list from a pandas series. Let’s create a list from the “wimbledon_winners” series using this function.

ls = list(wimbledon_winners) # check the type print(type(ls)) # print the content print(ls)
 ['Novak Djokovic', 'Andy Murray', 'Roger Federer', 'Novak Djokovic', 'Novak Djokovic']

You can see that the resulting list has all the values from the series “wimbledon_winners”.

With this, we come to the end of this tutorial. The code examples and results presented in this tutorial have been implemented in a Jupyter Notebook with a python (version 3.8.3) kernel having pandas version 1.0.5

Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.

Источник

How to convert a Pandas series into a Python list?

EasyTweaks.com

In this short tutorial we will describe a simple method for turning two or more pandas DataFrame column into a Python list object made of string values.

Use the following syntax to convert the contents of a Pandas series into a list object in Python:

your_list = your_pandas_series.to_list()

Read on for a step by step practical example.

Data Preparation

We’ll first import the pandas library and then define a Series object using the pd.Series constructor:

import pandas as pd office_series = pd.Series(['Bangalore', 'Osaka', 'Hong Kong', 'Paris', 'Osaka'])

Note: When creating the Series you might encounter the following type error:

#TypeError: Index(. ) must be called with a collection of some kind

The pd.Series function expects to receive an index value that is a collection; otherwise it will create one automatically. Make sure you pass a list to the Serires constructor or define the index as a collection.

Convert pandas Series to strings list

Now that we have a pandas Series defined we can easily convert it to a Python list:

office_lst = office_series.to_list() print ( office_lst )

This will return a list of strings as shown below

['Bangalore', 'Osaka', 'Hong Kong', 'Paris', 'Osaka']

Pandas Series to a dictionary object

We can extract a list into a dictionary object consisting on key/value pairs:

office_dict = office_series.to_dict()

Pandas Series to unique values

In our example above, we have seen that the value ‘Osaka’ appears twice in our Series. What if we want to ensure that our list contains only unique list of values?

One solution is to use the Series unique() method, which returns a Numpy array, we can then use the array tolist() method to create a list of distinct items:

unique_office_lst = office_series.unique().tolist() print(unique_office_lst)
['Bangalore', 'Osaka', 'Hong Kong', 'Paris']

The second option is to convert our list to a Python set object and then back to a list:

['Hong Kong', 'Bangalore', 'Paris', 'Osaka']

Note: we can use the Python list append() method to add the contents of the list we created to an existing list.

Pandas series index to list

If we would like to convert the Series index to a list we can use the following code:

Источник

Оцените статью