Home > database >  How can I map a list consisting of 136 rows to 7 columns
How can I map a list consisting of 136 rows to 7 columns

Time:03-01

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

CodePudding user response:

You can use numpy.shape 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

CodePudding user response:

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
  • Related