'Float64 and pandas: How to keep the number of significant digits in a file?
I have a csv file like the following:
x y
5.1 4.5
5.72 2.53
6.235 4.155
Please note the number of significant digits varies with the lines.
I would like to load it in python, make some calculations and save a new csv file with the number of digits by line respected. So, I want in output:
x y x+y x-y x*y
5.1 4.5 9.6 0.6 23.0
5.72 2.53 8.25 3.19 14.47
6.235 4.155 10.390 2.080 25.906
I did the following code:
import pandas as pd
# Import data from my file
#################################################################
# data_file = "Path.dat"
# data = open(data_file,"r")
# df = pd.read_csv(data,sep=' ')
##################################################################
# Creation of the dataframe without the file
df = pd.DataFrame({'x': {0: 5.1, 1: 5.72, 2: 6.235}, 'y': {0: 4.5, 1: 2.53, 2: 4.155}})
# Add new data
df.insert(2,'x+y',df['x'] + df['y'],True)
df.insert(3,'x-y',df['x'] - df['y'],True)
# Save the new file
# df.to_csv("Path.txt", index = False,sep=' ')
I have the following in output:
x y x+y x-y x*y
5.1 4.5 9.6 0.5999999999999996 22.95
5.72 2.53 8.25 3.19 14.471599999999999
6.235 4.155 10.39 2.08 25.906425000000002
I read this question but it is answered to use the float_format argument which will "fix" a number of digits in all the file like that:
x y x+y x-y x*y
5.100 4.500 9.600 0.600 22.950
5.720 2.530 8.250 3.190 14.472
6.235 4.155 10.390 2.080 25.906
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
