Home > database >  Python: Write 3 dimensional array to CSV file
Python: Write 3 dimensional array to CSV file

Time:06-25

I am trying to write a program that takes in data from a JSON file, puts it into arrays, and then writes the arrays into a CSV file for human-readability. I am already parsing the JSON file and the array comes out looking like this:

sensorTest = [[[1, 2, 3],
               [4, 5, 6],
               [7, 8, 9],
               [10, 11, 12]],
              [[13, 14, 15],
               [16, 17, 18],
               [19, 20, 21],
               [22, 23, 24]]]

I want this to be written to a CSV file so that the elements of each list are placed in their own column like this: The desired CSV output

Instead, out of everything I have tried, I keep getting something that essentially just places all the array elements in the first column like this: Bad output

I'll attach my code below.

import json
import csv
from os import walk
from os import path
import matplotlib.pyplot as plt
import numpy as np
from datetime import datetime

if __name__ == "__main__":
sensorBoard = [0, 1]
    with open("./Data/sensorData.csv", "w", encoding='utf8', newline='') as csvfile:
        csvfile.write("C1,C2,C3,C4,C5,C6,C7,C8\n")
        hrd = csv.writer(csvfile)   # hrd is human-readable data
        for board in sensorBoard:  # loop through element number of lists
            print(board)
            print(sensorTest[board])
            # print(sensorTest[board][0])
            # print(sensorTest[board][1])
            for channelIndex, channelVals in enumerate(sensorTest[board]):  # this grabs the set of values for the channel
                print(sensorTest[board][channelIndex])
                # hrd.writerow([str(sensorTest[board][channelIndex])])
                for valIndex, val in enumerate(sensorTest[board][channelIndex]):
                    hrd.writerow([str(val)])

CodePudding user response:

Let Python do more of the work for you:

data = sensorTest[0] sensorTest[1]
with open("output.csv", "w", encoding='utf8') as csvfile:
    hrd = csv.writer(csvfile)
    hrd.writerow(["C%d"%d for d in range(1,1 len(data))])
    for r in zip(*data):
        hrd.writerow(r)
  • Related