I am trying to convert a list of values in a Dataframe row into seperate columns
I have tried to use pivot,pivot_table and get_dummies but I couldnt get the expected result.
Actual Columns:
A B
1 [1, 3, 5]
2 [2, 4, 6]
Expected Output:
A B_1 B_2 B_3
1 1 3 5
2 2 4 6
One way:
df_out = df.set_index('A').explode('B')
df_out = df_out.set_index(df_out.groupby(level=0).cumcount() + 1, append=True).unstack()
df_out.columns = [f'{i}_{j}' for i, j in df_out.columns]
df_out.reset_index()
Output:
A B_1 B_2 B_3
0 1 1 3 5
1 2 2 4 6
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.