Ask Your Question
2

How to create multiple columns in a dataframe by separating a list and using one element as the column header?

asked 2022-01-29 11:00:00 +0000

woof gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2021-10-09 04:00:00 +0000

huitzilopochtli gravatar image

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.
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-01-29 11:00:00 +0000

Seen: 11 times

Last updated: Oct 09 '21