0

I have a list data=['CDs', 1, 'J12345','Rainbow', None, 'Styles', 2, 'J12345', 'Rainbow', None, 'Folk', 3, 'J12345', 'Rainbow', None] I would like to convert it to a pandas dataframe with fixed number of columns.

The result expected to be like:

category |  num | series  |  title |  brand |
'CDs'       1     J12345   Rainbow   None 
'Styles'    2     J12345   Rainbow   None 
'Folk'      3     J12345   Rainbow   None 
snakecharmerb
  • 47,570
  • 11
  • 100
  • 153
Anita
  • 281
  • 2
  • 9

3 Answers3

4

Setup

num_cols = 5
cols = ['category', 'num', 'series', 'title', 'brand']

numpy.reshape

d = np.reshape(data, (-1, num_cols))  
pd.DataFrame(d, columns=cols)

  category num  series    title brand
0      CDs   1  J12345  Rainbow  None
1   Styles   2  J12345  Rainbow  None
2     Folk   3  J12345  Rainbow  None
user3483203
  • 50,081
  • 9
  • 65
  • 94
1

You could do:

import pandas as pd

data = ['CDs', 1, 'J12345','Rainbow', None,
        'Styles', 2, 'J12345', 'Rainbow', None,
        'Folk', 3, 'J12345', 'Rainbow', None]

df = pd.DataFrame([data[i:i+5] for i in range(0, len(data), 5)], columns=['category', 'num', 'series',  'title', 'brand'])
print(df)

Output

  category  num  series    title brand
0      CDs    1  J12345  Rainbow  None
1   Styles    2  J12345  Rainbow  None
2     Folk    3  J12345  Rainbow  None

The statement:

[data[i:i+5] for i in range(0, len(data), 5)]

creates the following list of lists:

[['CDs', 1, 'J12345', 'Rainbow', None], ['Styles', 2, 'J12345', 'Rainbow', None], ['Folk', 3, 'J12345', 'Rainbow', None]]

The above can be pass to pandas directly.

Dani Mesejo
  • 61,499
  • 6
  • 49
  • 76
1

Almost same idea as @user3483203,

a = np.array(data)
nrows = 3
ncols = a.shape[0]//nrows
df = pd.DataFrame(a.reshape(nrows, ncols), columns=['category', 'num', 'series', 'title', 'brand'] )

    category    num series  title   brand
0   CDs         1   J12345  Rainbow None
1   Styles      2   J12345  Rainbow None
2   Folk        3   J12345  Rainbow None
Vaishali
  • 37,545
  • 5
  • 58
  • 86