How to Convert List to a Column in Pandas


You can use the following basic syntax to convert a list to a column in a pandas DataFrame:

df['new_column'] = pd.Series(some_list)

The following example shows how to use this syntax in practice.

Example: Convert List to a Column in Pandas

Suppose we have the following pandas DataFrame that contains information about various basketball players:

import pandas as pd

#create DataFrame
df = pd.DataFrame({'team': ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'],
                   'points': [18, 22, 19, 14, 14, 11, 20, 28],
                   'assists': [5, 7, 7, 9, 12, 9, 9, 4],
                   'rebounds': [11, 8, 10, 6, 6, 5, 9, 12]})

#view DataFrame
print(df)

  team  points  assists  rebounds
0    A      18        5        11
1    B      22        7         8
2    C      19        7        10
3    D      14        9         6
4    E      14       12         6
5    F      11        9         5
6    G      20        9         9
7    H      28        4        12

The following code shows how to convert a list called steals to a column in the DataFrame:

#create list
steals = [4, 4, 3, 2, 3, 5, 0, 1]

#convert list to DataFrame column
df['steals'] = pd.Series(steals)

#view updated DataFame
print(df)

  team  points  assists  rebounds  steals
0    A      18        5        11       4
1    B      22        7         8       4
2    C      19        7        10       3
3    D      14        9         6       2
4    E      14       12         6       3
5    F      11        9         5       5
6    G      20        9         9       0
7    H      28        4        12       1

Notice that steals has been added as a new column to the pandas DataFrame.

Note that if the list has fewer elements than the number of rows in the existing DataFrame, then NaN values will be filled in the column:

#create list
steals = [4, 4, 3, 2, 3]

#convert list to DataFrame column
df['steals'] = pd.Series(steals)

#view updated DataFame
print(df)

  team  points  assists  rebounds  steals
0    A      18        5        11     4.0
1    B      22        7         8     4.0
2    C      19        7        10     3.0
3    D      14        9         6     2.0
4    E      14       12         6     3.0
5    F      11        9         5     NaN
6    G      20        9         9     NaN
7    H      28        4        12     NaN

Notice that the last three values in the new steals column are simply NaN values generated by pandas.

Additional Resources

The following tutorials explain how to perform other common tasks in pandas:

How to Get Cell Value from Pandas DataFrame
How to Rename Index in Pandas DataFrame
How to Sort Columns by Name in Pandas

Leave a Reply

Your email address will not be published.