Convert Pandas Columns to Comma Separated List Using .tolist()
This article will explore different methods to convert a column to a comma-separated list using popular libraries like Pandas:
In this code, df['Name'].values.tolist()
converts the ‘Name’ column to a Python list.
Python3
import pandas as pd data = { 'Name' : [ 'Alice' , 'Bob' , 'Charlie' , 'David' ], 'Age' : [ 25 , 30 , 22 , 35 ]} df = pd.DataFrame(data) name_list = df[ 'Name' ].values.tolist() print ( "Comma-separated list of names:" , name_list) age_list = df[ 'Age' ].values.tolist() print ( "Comma-separated list of names:" , age_list) |
Output:
Comma-separated list of names: ['Alice', 'Bob', 'Charlie', 'David']
Comma-separated list of names: [25, 30, 22, 35]
Convert Column To Comma Separated List In Python
A comma-separated list in Python is a sequence of values or elements separated by commas. Pandas is a Python package that offers various data structures and operations for manipulating numerical data and time series.