import csv
import matplotlib.pyplot as plt
filename = r"C:\Users\name\Desktop\sampledata.csv"
with open(filename, newline='') as file:
reader = csv.reader(file)
header = next(reader)
data = []
for row in reader:
measured_time = float(row[0])
wv1 = float(row[1])
wv2 = float(row[2])
data.append([measured_time, wv1,wv2])
time=data[0]
y1=data[1]
plt.plot(time,y1)
plt.show()
工作得很好,但是在我使用真实数据之前这是一个测试。
现在,真实数据没有标题,只包含2列。
import csv
import matplotlib.pyplot as plt
filename = r"C:\Users\name\Desktop\real_data.csv"
with open(filename, newline='') as file:
reader = csv.reader(file,delimiter=';')
data = []
for row in reader:
measured_time = float(row[0])
wv1 = float(row[1])
data.append([measured_time, wv1])
time=data[0]
y1=data[1]
plt.plot(time,y1)
plt.show()
这会产生
时间= [100.1]
Y1 = [110,2]
所以基本上只是前两行,而第一个代码块正确地提取列
时间= [100 110 ...]
y1 = [1 2 ...]
当我使用
时会发生同样的事情import csv
import matplotlib.pyplot as plt
filename = r"C:\Users\name\Desktop\sampledata.csv"
with open(filename, newline='') as file:
reader = csv.reader(file)
header = next(reader)
data = []
for row in reader:
measured_time = float(row[0])
wv1 = float(row[1])
data.append([measured_time, wv1])
time=data[0]
y1=data[1]
plt.plot(time,y1)
plt.show()
现在我的解决方法是
data = np.array(data).astype("float")
time=data[:,0]
y1=data[:,1]
当然必须有更好的方法,我只是从Python开始。
使用的数据:
sample data
Time,279 nm,306 nm
0,100,150
1,110,175
2,125,230
3,130,245
real data
3.986931e+002;0.000000e+000
4.021733e+002;0.000000e+000
答案 0 :(得分:1)
list(zip())
允许对一组序列进行处理:
time = [100, 1]
y1 = [110, 2]
l = list(zip(time, y1))
print(l) # [(100, 110), (1, 2)]
time = l[0] # (100, 110)
y1 = l[1] # (1, 2)
它们是可以用作列表的元组,或者您可以将它们转换为列表:
time = list(l[0]) # [100, 110]
y1 = list(l[1]) # [1, 2]
如果你想直接进入相反的形式,你可以交换阅读部分:
import csv
import matplotlib.pyplot as plt
filename = r"C:\Users\name\Desktop\sampledata.csv"
with open(filename, newline='') as file:
reader = csv.reader(file)
# header = next(reader)
time = []
y1 = []
for row in reader:
time.append( float(row[0]) )
y1.append( float(row[1]) )
plt.plot(time,y1)
plt.show()