如何截断 CSV 文件中的双变量 python
How to truncate double variables in CSV files python
我有一个 CSV 文件,其中包含经度和纬度等列。看起来像:
经度纬度
-99.148144 19.503343
-99.148311 19.503349
-99.148242 19.503267
-99.138863 19.474553
-99.148239 19.503267
但是,我想制作一个新的 CSV 文件(我知道该怎么做),但是在这个新的 CSV 文件中,我只想要点后的 3 位数字,例如:
经度纬度
-99.148 19.503
-99.148 19.503
-99.148 19.503
-99.138 19.474
-99.148 19.503
PS:我正在使用 python 和 pandas 的本地库来管理 CSV 文件
您可以在写入CSV文件时使用格式化打印。例如:
with open("output.csv", 'a') as outfile:
outfile.write("Datapoint: %.3f\n" % (3.14159))
它的工作方式与 C/C++ 中的 printf 非常相似。
这可行,但被认为是一种已弃用的格式样式。您还可以使用更新的 .format 方法:
with open("output.csv", 'a') as outfile:
outfile.write("Datapoint: {:.3f}\n".format(3.14159))
如果您需要更复杂的东西,这里有一个其他格式标记的列表以及这两种方法的更多示例:
http://www.python-course.eu/python3_formatted_output.php
我有一个 CSV 文件,其中包含经度和纬度等列。看起来像:
经度纬度
-99.148144 19.503343
-99.148311 19.503349
-99.148242 19.503267
-99.138863 19.474553
-99.148239 19.503267
但是,我想制作一个新的 CSV 文件(我知道该怎么做),但是在这个新的 CSV 文件中,我只想要点后的 3 位数字,例如:
经度纬度
-99.148 19.503
-99.148 19.503
-99.148 19.503
-99.138 19.474
-99.148 19.503
PS:我正在使用 python 和 pandas 的本地库来管理 CSV 文件
您可以在写入CSV文件时使用格式化打印。例如:
with open("output.csv", 'a') as outfile:
outfile.write("Datapoint: %.3f\n" % (3.14159))
它的工作方式与 C/C++ 中的 printf 非常相似。
这可行,但被认为是一种已弃用的格式样式。您还可以使用更新的 .format 方法:
with open("output.csv", 'a') as outfile:
outfile.write("Datapoint: {:.3f}\n".format(3.14159))
如果您需要更复杂的东西,这里有一个其他格式标记的列表以及这两种方法的更多示例: http://www.python-course.eu/python3_formatted_output.php