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:
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
Asked: 2022-01-29 11:00:00 +0000
Seen: 11 times
Last updated: Oct 09 '21