Sarah
Sarah

Reputation: 107

Pandas to_csv outputs misaligned data

This functions writes a CSV:

def onNewData(self, data):  
    zvalues = []
    csv = open("data.csv","w+")
    columnTitleRow = " ValuesofX , ValuesofY , ValuesofZ \n"
    csv.write(columnTitleRow)
    for i in range(data.getNumPoints()):
        zvalues.append(data.getZ(i))
        csv.write((str(data.getX(i))+',')+(str(data.getY(i))+',') + (str(data.getZ(i))+','))   
        csv.write('\n') 
    csv.close()  
    zarray = np.asarray(zvalues)
    p = zarray.reshape (-1, data.width)        
    self.queue.put(p)

I use this to read my CSV:

# reading data
  import pandas as pd
  import numpy as np 

  bolts_data = pd.read_csv("data.csv")
  print(bolts_data)

This is the code that I have written to save the data directly into a CSV file. However when I run a new program to read the CSV file, the data shown is misaligned from the header. This error can be shown in the first picture below. The ideal output that I wish to see is the second picture shown below. Is there any possible solution to fix the misalignment?

Misaligned from the header Misaligned from the header

This is the output that I wish to see This is the output that i wish to see

Upvotes: 1

Views: 1208

Answers (2)

Josh Friedlander
Josh Friedlander

Reputation: 11657

I believe if you use index_col=False in your read_csv call, it will fix this issue.

Upvotes: 1

Hima
Hima

Reputation: 12054

There is a Problem in your definition. It generates an extra Column

Code Modification : You do not need comma after ValuesofZ

def onNewData(self, data):  
    zvalues = []
    csv = open("data.csv","w+")
    columnTitleRow = " ValuesofX , ValuesofY , ValuesofZ \n"
    csv.write(columnTitleRow)
    for i in range(data.getNumPoints()):
        zvalues.append(data.getZ(i))
        csv.write((str(data.getX(i))+',')+(str(data.getY(i))+',') + (str(data.getZ(i))))    #Here  
        csv.write('\n') 
    csv.close()  
    zarray = np.asarray(zvalues)
    p = zarray.reshape (-1, data.width)        
    self.queue.put(p)

Upvotes: 2

Related Questions