Create a new list from a colum in a dataframe
Let's assume you have a pandas DataFrame df
with a column named column_name
. You can create a new list from this column using the following methods:
Method 1: Using the tolist()
method
new_list = df['column_name'].tolist()
This will create a new list containing all the values in the column_name
column.
Method 2: Using the values.tolist()
method
new_list = df['column_name'].values.tolist()
This is similar to the previous method, but uses the values
attribute to access the column values.
Method 3: Using a list comprehension
new_list = [x for x in df['column_name']]
This creates a new list by iterating over the values in the column_name
column.
Method 4: Using the numpy.array()
function
import numpy as np
new_list = np.array(df['column_name']).tolist()
This creates a NumPy array from the column values and then converts it to a list.
All of these methods will create a new list from the values in the column_name
column. You can choose the one that best fits your needs.