Home > Back-end >  Can't get my dataframe to not return float so I can get rid of decimal
Can't get my dataframe to not return float so I can get rid of decimal

Time:08-10

I can't seem to change to datatype of my dataframe so that it could be int (or 'int64'). I have a long list of columns where I want to apply 'int' or 'int64' to all of them instead of specific columns. The reason for the change is so that I could not show the decimal. (For ex. it returning 52 instead of 52.0). Here is a small example of a dataframe and it not changing the datatypes and the desired output at the bottom.

data = {'sand depth': [52.0, 22.0],
      'ground depth': [45.0, 84.0]}
df = pd.DataFrame(data)
df.dtypes
m=(df.dtypes=='float64')
df.loc[:,m]=df.loc[:,m].astype(int)
df.dtypes

desired output

data = {'sand depth': [52, 22],
      'ground depth': [45, 84]}
df = pd.DataFrame(data)
df.dtypes

CodePudding user response:

This doesn't really happen because of dtype but rather pandas' formatting numerical values, you can adjust the display format by specifying it:

pd.options.display.float_format = '{:,.0f}'.format

Should take care of it.

CodePudding user response:

try df = df.astype(int,errors='ignore')

errors ignore part is to not raise errors it you have any columns that cant be converting to int

CodePudding user response:

This can be done like so:

>>> data = {'sand depth': [52.0, 22.0],
      'ground depth': [45.0, 84.0], 'extra_col': ['foo', 'bar']}
>>> df = pd.DataFrame(data)
>>> df
   sand depth  ground depth extra_col
0        52.0          45.0       foo
1        22.0          84.0       bar
>>> m = df.columns[(df.dtypes == 'float64')].tolist()
>>> df[m] = df[m].astype(int)
>>> df
   sand depth  ground depth extra_col
0          52            45       foo
1          22            84       bar

Seems assigning with .loc doesn't change the dtype, but assigning the entire column does. I also added an extra column to convert it wouldn't convert non-float columns.

  • Related