Pandas data frame. Change float format. Keep type “float”

我的未来我决定 提交于 2019-12-11 04:04:16

问题


I'm trying to change a format of pd data frame column without changing the type of data. Here is what I have: df = pd.DataFrame({'Age': [24.0, 32.0}])

I'd like to represent Age in 24 32 type or 24.00 32.00 and keep them as floats. Here is what I can do:

df['Age'].map('{:,.2f}'.format)

But this line changes the type of data to object. I was also trying to apply: `

df = df.style.format({'Age': '{:,.2f}'.format})`

but there is something wrong in it. Please help to figure out the right way.


回答1:


Your dataFrame itself a type float.

Dataframe:

>>> df
    Age
0  24.0
1  32.0

Check DataFrame type:

>>> df.dtypes
Age    float64
dtype: object

check dtype for DataFrame column type:

>>> df.Age
0    24.0
1    32.0
Name: Age, dtype: float64

OR even check like:

>>> df['Age'].dtype.kind
'f'

The way you are using to round up double digit zeros that's correct but converting them again to float will get them remain in single zero as being float.

>>> df['Age'].map('{:,.2f}'.format)
0    24.00
1    32.00
Name: Age, dtype: object

As you are interested keeping either mimic like int values 24, 32 or 24.00 & 32.00, if you are only interested in the display of floats then you can do pd.set_option('display.float_format','{:.0f}'.format), which doesn't actually affect your data.

For Floating Format without leading zeros

>>> pd.set_option('display.float_format','{:.0f}'.format)
>>> df
   Age
0   24
1   32

>>> df.dtypes
Age    float64
dtype: object

For Floating Format

>>> pd.set_option('display.float_format','{:.2f}'.format)
>>> df
    Age
0 24.00
1 32.00
>>> df.dtypes
Age    float64
dtype: object

Alternative way

Set the display precision option:

>>> pd.set_option('precision', 0)
>>> df
   Age
0   24
1   32

>>> df.dtypes
Age    float64
dtype: object


来源:https://stackoverflow.com/questions/54378389/pandas-data-frame-change-float-format-keep-type-float

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!