我有一个CSV文件(带有CNC数据),该文件有大约10,000行和六列。我需要阅读x,y和z坐标的第4、5和6列,并使用matplotlib构建3D图形。
有人可以帮助您从csv文件中读取特定列吗?
这就是我现在拥有的:
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()
答案 0 :(得分:1)
我认为您会发现pandas可以满足您的需求。它具有一些出色的数据处理工具。
示例代码:
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]
其余代码(绘图等)应保持不变
答案 1 :(得分:0)
我真的不知道什么是CNC数据,但我确实知道如何从CSV文件读取特定的列。
希望我的代码可以为您提供帮助。
csv数据
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
阅读4,5,6列
#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)
输出
['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']