【问题标题】:Format number of decimals in data written to CSV file格式化写入 CSV 文件的数据中的小数位数
【发布时间】:2015-06-30 08:03:54
【问题描述】:

我有这段代码用于从 Picotech 的 TC-08 温度记录器读取温度并将温度写入 CSV 文件。问题是温度以四位小数存储在文件中,两位小数甚至一位对我来说已经足够了。

我尝试使用 np.around(temp,2) 和 np.set_printoptions(precision=2) 但它们都不会更改写入 CSV 文件的小数位数。你能帮我告诉我正确的方法吗?

csv_delimiter='\t'  
file = 'test.csv'   
no_of_channels=6    #set number of channels to read
tc_type=ord('K')    #set type of element
no_of_meas = 10
time_interval= 10 #read every 10 sec

#Setup TC08
mydll = ctypes.windll.LoadLibrary('usbtc08.dll')
device = mydll.usb_tc08_open_unit()
mydll.usb_tc08_set_mains(device,50) #set the mains rejection to 50 or 60 Hz

temp = np.zeros( (9,), dtype=np.float32)
overflow_flags = np.zeros( (1,), dtype=np.int16)
mydll.usb_tc08_set_channel(device, 0, 0 )

no_of_channels +=1  #Don't want to read channel 0

for i in range(1,no_of_channels):
    mydll.usb_tc08_set_channel(device,i,tc_type)

cur_meas = 1

with open(file, 'a', newline='') as fp:
    while cur_meas <= no_of_meas:
        timeBegin = time.time()
        cur_time = datetime.datetime.strftime(datetime.datetime.now(), '%H:%M:%S') 
        a = csv.writer(fp, delimiter=csv_delimiter)
        mydll.usb_tc08_get_single(device, temp.ctypes.data, overflow_flags.ctypes.data, 0)       
        #np.around(temp,2)#I have tried this in order to get two decimals
        #np.set_printoptions(precision=2)#I have tried this in order to get two decimals
        print(temp)
        listtemp = temp[1:no_of_channels]
        print(listtemp)
        data = [[cur_time]+list(listtemp)]
        a.writerows(data)
        fp.flush() 
        os .fsync(fp.fileno())
        print(', '.join(map(str, data)))
        cur_meas += 1
        timeEnd = time.time()
        timeElapsed = timeEnd - timeBegin
        time.sleep(time_interval-timeElapsed)

mydll.usb_tc08_close_unit(device)

【问题讨论】:

标签: python numbers decimal


【解决方案1】:

显而易见,csv 是文本,因此每个单元格导入时显示的精度可能不同。 round 函数不保证两位小数的精度,但格式化浮点数可以。

f1 = 100.0001
f2 = 99.2345
f3 = 88.7455
f4 = 1.4589
lf1 = [f1, f2, f3, f4]

for f in lf1:
    print f
    print str(round(f, 2))
    print '{0:0.2f}'.format(f) # rounds and formats to two decimal precision

100.0001
100.0
100.00
99.2345
99.23
99.23
88.7455
88.75
88.75
1.4589
1.46
1.46

【讨论】:

  • 谢谢。我担心 CSV 是文本,但我希望如果我在将临时数组中的数字写入 CSV 文件之前对其进行格式化,它们将以两位小数的精度保存。
猜你喜欢
  • 2015-04-28
  • 1970-01-01
  • 1970-01-01
  • 2018-09-03
  • 1970-01-01
  • 2016-11-12
  • 2011-03-27
  • 2019-09-22
  • 2020-11-30
相关资源
最近更新 更多