0

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
2
  • df[['A']].join(pd.DataFrame(df.B.tolist(),columns=[f'B_{i+1}' for i in range(df.B.str.len().max())])) Commented Aug 31, 2019 at 18:03
  • Possible duplicate of Pandas split column of lists into multiple columns Commented Sep 1, 2019 at 18:20

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.