Reputation: 13
I have a CSV file (with CNC data) which has about 10,000 lines and six columns. I need to read the columns 4, 5 and 6 which are x, y and z coordinates, and build a 3D graph by using matplotlib.
Can someone help how to read a certain column from csv file?
This is what i have right now:
import numpy as np
import json
from datetime import datetime
from numpy import genfromtxt
from datetime import timezone
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import axes3d
import csv
data_open = open("cnc_data.txt").read()
data_open = data_open.split("\n")
data=[]
tmp=[]
for x in range (len(data_open)):
data.append(json.loads (data_open[x]))
data[x]["timestamp"]=datetime.strptime(data[x]["timestamp"], '%Y-%m-%d %H:%M:%S.%f')
data[x]["timestamp"]=data[x]["timestamp"].replace(tzinfo=timezone.utc).timestamp()
tmp.append(list(data[x].values()))
np.savetxt("CNC.csv", tmp, fmt='%f')
figure = plt.figure()
axis = figure.add_subplot(1,1,1, projection = '3d')
h=0
while h < len(data) :
X= [data[h]["analogInputValueX"]]
Y= [data[h]["analogInputValueY"]]
Z= [data[h]["analogInputValueZ"]]
print (X)
print (Y)
print (Z)
h = h + 1
plt.plot(X, Y, Z)
axis.set_xlabel('x-axis')
axis.set_ylabel('y-axis')
axis.set_zlabel('z-axis')
plt.show()
Upvotes: 1
Views: 128
Reputation: 651
I dont really know what is CNC data, but I do know how to read specific columns from CSV file.
I hope my code can help you.
csv data
1,2,3,4,5,6
1,2,3,4,5,6
1,2,3,4,5,6
1,2,3,4,5,6
1,2,3,4,5,6
1,2,3,4,5,6
1,2,3,4,5,6
1,2,3,4,5,6
1,2,3,4,5,6
1,2,3,4,5,6
READ 4,5,6 COCLUMNS
#open file
fo = open("test.csv")
#create empty list
ls = []
x_columns = []
y_columns = []
z_columns = []
#read data row by row
for line in fo:
line = line.replace("\n","")
ls = list(line.split(","))
x_cloumns.append(ls[3])
y_cloumns.append(ls[4])
z_cloumns.append(ls[5])
fo.close
print(x_columns,y_columns,z_columns)
output
['4', '4', '4', '4', '4', '4', '4', '4', '4', '4']
['5', '5', '5', '5', '5', '5', '5', '5', '5', '5']
['6', '6', '6', '6', '6', '6', '6', '6', '6', '6']
Upvotes: 0
Reputation: 1246
I think you'll find pandas good for your needs. It has some terrific data manipulation tools.
Example code:
import pandas as pd
df = pd.read_csv('/path/to/csv/file') # You can use the 'delimiter' argument to specify a delimiter of your choosing
x_column = df.iloc[:, 3]
y_column = df.iloc[:, 4]
z_column = df.iloc[:, 5]
Rest of the code (plotting etc.) should stay the same
Upvotes: 1