问题描述
我正在尝试更改pd数据框列的格式而不更改数据类型.这是我所拥有的:df = pd.DataFrame({'Age': [24.0, 32.0}])
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}])
我想用24 32
类型或24.00 32.00
表示Age,并将它们保持为浮点数.这是我可以做的:
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.
推荐答案
您的dataFrame本身为float类型.
Your dataFrame itself a type float.
数据框:
>>> df
Age
0 24.0
1 32.0
检查DataFrame类型:
Check DataFrame type:
>>> df.dtypes
Age float64
dtype: object
检查dtype是否为DataFrame列类型:
check dtype for DataFrame column type:
>>> df.Age
0 24.0
1 32.0
Name: Age, dtype: float64
甚至检查如下:
>>> 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
由于您希望保持类似int值24, 32
或24.00 & 32.00
这样的模拟,如果仅对浮点数的显示感兴趣,则可以执行pd.set_option('display.float_format','{:.0f}'.format)
,这实际上不会影响您的数据.
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.
>>> pd.set_option('display.float_format','{:.0f}'.format)
>>> df
Age
0 24
1 32
>>> df.dtypes
Age float64
dtype: object
对于浮动格式
>>> 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
这篇关于 pandas 数据框.更改浮动格式.保持类型为"float"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!