Importing a .csv file given by
JavaScript
x
4
1
a
2
1.4
3
1.12
4
leads to an addition of a trailing zero in the first line. How to avoid it?
Advertisement
Answer
This is just the visual representation of the float data in your df
. If you want it different, change the format string for it.
For your numbers '{:,g}'
would work (see format specification mini language – scroll down for the table that explains it).
Example:
JavaScript
1
18
18
1
import pandas as pd
2
import numpy as np
3
4
with open("data.txt","w") as f:
5
f.write("an1.4n1.12")
6
7
df = pd.read_csv("data.txt")
8
print(df)
9
10
# change the way floats are formatted
11
pd.options.display.float_format = '{:,.06f}'.format
12
13
# change the way floats are formatted
14
pd.options.display.float_format = '{:,g}'.format
15
16
df = pd.read_csv("data.txt")
17
print(df)
18
Output:
JavaScript
1
16
16
1
# default formatting
2
a
3
0 1.40
4
1 1.12
5
6
7
# {:,06f}
8
a
9
0 1.400000
10
1 1.120000
11
12
# {:,g}
13
a
14
0 1.4
15
1 1.12
16
From a numerical standpoint there is no difference between 1.4 and 1.40 or 00001.40000000000.
Guarav Kumar’s suggestion to use
JavaScript121df = pd.read_csv('minExamp.csv' , dtype = str)
2
is bad advice – it changes the data type for the (single) column to be of type string.
This will prevent you from calculating anything with the numbers of your dataframe.