import numpy as np
import pandas as pd
Consider the following simple DataFrame
df = pd.DataFrame([[1,2],[3,4]])
It has the following types:
df.dtypes
0 int64 1 int64 dtype: object
However, if we append another row that contain a float
df2 = pd.concat([df, pd.DataFrame([[10.,11]])])
df2
0 | 1 | |
---|---|---|
0 | 1 | 2 |
1 | 3 | 4 |
0 | 10 | 11 |
Then, we see that the type of the first column is changed to a float
df2.dtypes
0 float64 1 int64 dtype: object
This is not so bad... at the momment. But if we change the DataFrame further:
df3 = pd.concat([df, pd.DataFrame([[10.1,11]])])
df3
0 | 1 | |
---|---|---|
0 | 1.0 | 2 |
1 | 3.0 | 4 |
0 | 10.1 | 11 |
This is already annoying. The integers (that were casted into floats) are now printed as floats. A workaround is to define a printing function:
def printFloat(x):
if np.modf(x)[0] == 0:
return str(int(x))
else:
return str(x)
and pass it to Pandas:
pd.options.display.float_format = printFloat
Now, printing df3 yields:
df3
0 | 1 | |
---|---|---|
0 | 1 | 2 |
1 | 3 | 4 |
0 | 10.1 | 11 |