How to split a list every N values into a dataframe columns and rows with python using pandas

Viewed 1230

Here is what I have, a list with 8 values, and want to split into 4 columns, which means I'd get 2 rows:

list = ['Jan 01 2020', '51.62', '51.87', '50.69', 'Jan 02 2020', '51.98', '52.14', '51.48']

columnNames = ['Date', 'A', 'B', 'C']

And, here what I expect to get:

Date        A     B     C

Jan 01 2020 51.62 51.87 50.69

Jan 02 2020 51.98 52.14 51.48

I tried this, but I don't know how to make it jump to another row after reading 4th, 8th, 12th,... value (I have a way bigger list actually)

import pandas as pd

list = ['Jan 01 2020', '51.62', '51.87', '50.69', 'Jan 02 2020', '51.98', '52.14', '51.48']

columnNames = ['Date', 'A', 'B', 'C']

df = pd.DataFrame(list, columns = columnNames)

print(df)
3 Answers
df = pd.DataFrame([list[n:n+4] for n in range(0, len(list), 4)], columns=columnNames)

You just need to splice the list into 4 elements each.

PS: it is a bad idea to name your variable as list

Split list into 2. I prefer the splitting method below because it will still work with nth length of the list

l1 = list[:len(lst)//2]
l2 = list[len(lst)//2:]

Create DatFrame

df = pd.DataFrame([l1, l2],columns =columnNames) 

enter image description here

Use np.array_split to split your array into 2 equal parts:

In [65]: import numpy as np

In [61]: l1,l2 = np.array_split(list, 2)    
In [42]: columnNames = ['Date', 'A', 'B', 'C']

In [44]: df = pd.DataFrame([l1, l2], columns=columnNames)    
In [45]: df
Out[45]: 
          Date      A      B      C
0  Jan 01 2020  51.62  51.87  50.69
1  Jan 02 2020  51.98  52.14  51.48
Related