Home > Enterprise >  How to group a list into a dataframe with four columns?
How to group a list into a dataframe with four columns?

Time:11-15

Let's assume I have a list similar to the one below:

l = ['A','B','C','D','E','F','G','H','I','L','M','N']

I want to create a dataframe that has 4 columns from the fact that every 4 objects in the list is a row. The outcome should be a dataframe with the following form:

Col1   Col2   Col3   Col4

  A     B       C     D
  
  E     F       G     H

  I     L       M      N

Can anyone help me do it?

Thanks!

CodePudding user response:

Convert values to numoy array and then use reshape:

l = ['A','B','C','D','E','F','G','H','I','L','M','N']
df = pd.DataFrame(np.array(l).reshape(-1, 4)).add_prefix('col')
print(df)
  col0 col1 col2 col3
0    A    B    C    D
1    E    F    G    H
2    I    L    M    N
  • Related