'How can I map a list consisting of 136 rows to 7 columns

I can't seem to find a way of doing the following:

I have a list of values consisting of 136 rows that looks like this

['0.32',
 '0.32',
 '0',
 '0.32',
 '0.32',
 'ABCTRANS',
 '0.00',
 '0',
 '1.96',
 '1.96',
 '0',
 '1.96',
 '1.96',
 'ACADEMY',
 '0.00',
 '0'
...up to 136]

Now I want to create a pandas DataFrame of 7 columns with the column names ['Low', 'OPEN', 'Volume', 'Close', 'High', 'Symbol', 'CHANGE', 'Trades'] with each 7 row mapped under the columns like

Low   Open   Volume  close  High  symbol     change    Trades
0.32   0.32    0      0.32  0.32  ABCFRANS     0       0.0
1.96   1.96    0      1.96  1.96  ACADEMY      0       00 
...      ...      ..     ...   ...   ....         ..       ..

UP TO THE 136th row



Solution 1:[1]

Use np.reshape:

import pandas as pd
import numpy as np

lst = ['0.32', '0.32', '0', ...up to 136]
cols = ['Low', 'OPEN', 'Volume', 'Close', 'High', 'Symbol', 'CHANGE', 'Trades']

df = pd.DataFrame(np.reshape(lst, (-1, 8)), columns=cols)
df = df.apply(pd.to_numeric, errors='ignore')

Output:

>>> df
    Low  OPEN  Volume  Close  High    Symbol  CHANGE  Trades
0  0.32  0.32       0   0.32  0.32  ABCTRANS     0.0       0
1  1.96  1.96       0   1.96  1.96   ACADEMY     0.0       0

>>> df.dtypes
Low       float64
OPEN      float64
Volume      int64
Close     float64
High      float64
Symbol     object
CHANGE    float64
Trades      int64
dtype: object

Solution 2:[2]

You can use numpy.reshape to do what you want.

import numpy as np
import pandas as pd

headers = ['Low', 'OPEN', 'Volume', 'Close', 'High', 'Symbol', 'CHANGE', 'Trades']

a = ['0.32',
 '0.32',
 '0',
 '0.32',
 '0.32',
 'ABCTRANS',
 '0.00',
 '0',
 '1.96',
 '1.96',
 '0',
 '1.96',
 '1.96',
 'ACADEMY',
 '0.00',
 '0']

aa = np.reshape(a, (2,8))

df = pd.DataFrame(aa)
df.columns = headers

Solution 3:[3]

here is one way:

import pandas as pd
li = ['0.32', '0.32', '0', '0.32', '0.32', 'ABCTRANS', '0.00', '0', '1.96', '1.96', '0', '1.96', '1.96', 'ACADEMY', '0.00', '0']
column_list = ['Low', 'OPEN', 'Volume', 'Close', 'High', 'Symbol', 'CHANGE', 'Trades']

data = [li[i:i+len(column_list)] for i in range(0,len(li),len(column_list))]
df = pd.DataFrame(data, columns=column_list)

output:

>>>
    Low  OPEN Volume Close  High    Symbol CHANGE Trades
0  0.32  0.32      0  0.32  0.32  ABCTRANS   0.00      0
1  1.96  1.96      0  1.96  1.96   ACADEMY   0.00      0

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Corralien
Solution 2
Solution 3