gpt4 book ai didi

python - 我想在 csv 文件中对小数点后 4 位小数的 4 列进行四舍五入

转载 作者:行者123 更新时间:2023-12-01 02:57:55 25 4
gpt4 key购买 nike

我的输入是

status,avgMeasuredTime,avgSpeed,extID,medianMeasuredTime,TIMESTAMP,vehicleCount,_id,REPORT_ID,Lat1,Long1,Lat2,Long2,Distance between 2 points,duration of measurements,ndt in kmh
OK,74,50,668,74,1406859600,5,20746220,158324,56.23172069428216,10.104986076057457,56.23172069428216,56.22579478256016,1030,52,71
OK,926,4,981,926,1412098500,0,28060227,210173,56.20913963031665,10.246642527612721,56.20913963031665,56.2026461982616,1106,88,45

预期输出:

status,avgMeasuredTime,avgSpeed,extID,medianMeasuredTime,TIMESTAMP,vehicleCount,_id,REPORT_ID,Lat1,Long1,Lat2,Long2,Distance between 2 points,duration of measurements,ndt in kmh
OK,74,50,668,74,1406859600,5,20746220,158324,56.2317,10.1050,56.2317,56.2258,1030,52,71
OK,926,4,981,926,1412098500,0,28060227,210173,56.2091,10.2466,56.2091,56.2026,1106,88,45

如您所见,我想对第 10、11、12、13 列进行四舍五入。

请帮忙。提前致谢。

最佳答案

awk方法:

awk 'BEGIN{FS=OFS=","}NR>1{for(i=NF-3;i>NF-7;i--) $i=sprintf("%.4f",$i)}1' file

输出:

status,avgMeasuredTime,avgSpeed,extID,medianMeasuredTime,TIMESTAMP,vehicleCount,_id,REPORT_ID,Lat1,Long1,Lat2,Long2,Distance between 2 points,duration of measurements,ndt in kmh
OK,74,50,668,74,1406859600,5,20746220,158324,56.2317,10.1050,56.2317,56.2258,1030,52,71
OK,926,4,981,926,1412098500,0,28060227,210173,56.2091,10.2466,56.2091,56.2026,1106,88,45
<小时/>

for(i=NF-3;i>NF-7;i--) - 从末尾的第 4 个字段开始迭代 4 个字段

<小时/>

注意:如果列数始终是静态的,您可以通过其位置号直接访问它们:

awk 'BEGIN{FS=OFS=","}NR>1{for(i=10;i<=13;i++) $i=sprintf("%.4f",$i)}1' file
<小时/>

如果您想要Python方法 - 我们开始:

with open("yourfile", 'r') as f:
for k,l in enumerate(f.read().splitlines()):
if k > 0:
items = l.split(',')
items[-4:-8:-1] = ["%.4f" % float(i) for i in items[-4:-8:-1]]
l = ','.join(items)
print(l)

输出将是相同的

关于python - 我想在 csv 文件中对小数点后 4 位小数的 4 列进行四舍五入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44046046/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com