Home > Net >  How to save data column wise in csv files from multiple list of list
How to save data column wise in csv files from multiple list of list

Time:02-03

We can save data column-wise in a CSV file from list (multiple lists) using pandas

listA = [1,2,3]
listB = [3,5,6]

pd.DataFrame({'A': listA, 'B': listB}).to_csv('file.csv', index=False)

When we have a list of lists we can save data into a CSV file using pandas

listA = [[1, 2, 3], [4, 5, 6]]
my_df = pd.DataFrame(listA)
my_df.to_csv('my_csv.csv', index=False, header=False)

Now, say I have a list of lists like the below one, the shape is (2, 3, 3)

listA = [[[1, 2, 3], [4, 5, 6], [7, 8, 9]], [[10, 20, 30], [40, 50, 60], [70, 80, 90]]]
listB = [[[a, b, c], [d, e, f], [g, h, i]], [[a0, b0, c0], [d0, e0, f0], [g0, h0, i0]]]
listC = [[[A, B, C], [D, E, F], [G, H, I]], [[A0, B0, C0], [D0, E0, F0], [G0, H0, I0]]]

and want to save them in a CSV file-1 that looks like

First   Second  Third   Fourth    Fifth   Sixth   Seven   Eight   Nine
1       a       A       4         d       D       7       g       G 
2       b       B       5         e       E       8       h       H 
3       c       C       6         f       F       9       i       I 

and another CSV file-2 for the rest of the data that contains 0 in the same pattern as CSV file-1.

Any idea is appreciated.

CodePudding user response:

first convert lists to numpy arrays

listA = np.array([[[1, 2, 3], [4, 5, 6], [7, 8, 9]], [[10, 20, 30], [40, 50, 60], [70, 80, 90]]])
listB = np.array([[[10, 20, 30], [40, 50, 60], [70, 80, 90]] , [[1, 2, 3], [4, 5, 6], [7, 8, 9]]])

next mix hetro-geniously all the arrays

a=np.vstack(np.vstack(np.stack((listA,listB),axis=2)))

output:

array([[ 1,  2,  3],
       [10, 20, 30],
       [ 4,  5,  6],
       [40, 50, 60],
       [ 7,  8,  9],
       [70, 80, 90],
       [10, 20, 30],
       [ 1,  2,  3],
       [40, 50, 60],
       [ 4,  5,  6],
       [70, 80, 90],
       [ 7,  8,  9]])

Form a Dataframe:

pd.DataFrame(a).T

output:

    0   1   2   3   4   5   6   7   8   9   10  11
0   1   10  4   40  7   70  10  1   40  4   70  7
1   2   20  5   50  8   80  20  2   50  5   80  8
2   3   30  6   60  9   90  30  3   60  6   90  9

you just need to name the columns and use to_csv to get a csv.

in your case just re place this line and rest will work as you expected.

a=np.vstack(np.vstack(np.stack((listA,listB,listC),axis=2)))
  •  Tags:  
  • Related