Ask Your Question

Revision history [back]

Assuming you have a dataframe with a column consisting of lists and you want to create new columns from the elements of these lists while using one specific element as the column header, you can achieve this with the following code:

import pandas as pd

# create example dataframe
df = pd.DataFrame({'list_col': [['A', 1, 2], ['B', 3, 4]]})

# extract column names from first list
col_names = df['list_col'].iloc[0]

# loop over list_col and create new columns
for i, col in enumerate(col_names):
    df[col] = [row[i] for row in df['list_col']]

# drop original list_col column
df.drop('list_col', axis=1, inplace=True)

# show resulting dataframe
print(df)

This code produces the following output:

   A  B
0  1  3
1  2  4

Explanation:

  • First, a new dataframe is created with an example column 'list_col' that consists of two lists.
  • The column names are extracted from the first list of 'list_col'.
  • Then, for each element of the column names, a new column is created by iterating over 'list_col' and extracting the respective element from each list.
  • Finally, the original 'list_col' column is dropped from the dataframe.