Python 如何删除熊猫中的小数点
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37084812/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to remove decimal points in pandas
提问by Amani
I have a pandas data frame, df, which looks like this:
我有一个 Pandas 数据框 df,如下所示:
Cut-off <=35 >35
Calcium 0.0 1.0
Copper 1.0 0.0
Helium 0.0 8.0
Hydrogen 0.0 1.0
How can I remove the decimal point so that the data frame looks like this:
如何删除小数点以使数据框如下所示:
Cut-off <= 35 > 35
Calcium 0 1
Copper 1 0
Helium 0 8
Hydrogen 0 1
I have tried df.round(0)
without success.
我试过df.round(0)
没有成功。
回答by Alexander
You have a few options...
你有几个选择...
1) convert everything to integers.
1)将所有内容转换为整数。
df.astype(int)
<=35 >35
Cut-off
Calcium 0 1
Copper 1 0
Helium 0 8
Hydrogen 0 1
2) Use round
:
2)使用round
:
>>> df.round()
<=35 >35
Cut-off
Calcium 0 1
Copper 1 0
Helium 0 8
Hydrogen 0 1
but not always great...
但并不总是很好...
>>> (df - .2).round()
<=35 >35
Cut-off
Calcium -0 1
Copper 1 -0
Helium -0 8
Hydrogen -0 1
3) Change your display precision option in Pandas.
3) 更改 Pandas 中的显示精度选项。
pd.set_option('precision', 0)
>>> df
<=35 >35
Cut-off
Calcium 0 1
Copper 1 0
Helium 0 8
Hydrogen 0 1
回答by joelostblom
Since pandas 0.17.1 you can set the displayed numerical precision by modifying the style of the particular data framerather than setting the global option:
从 pandas 0.17.1 开始,您可以通过修改特定数据框的样式而不是设置全局选项来设置显示的数值精度:
import pandas as pd
import numpy as np
np.random.seed(24)
df = pd.DataFrame(np.random.randn(5, 3), columns=list('ABC'))
df
df.style.set_precision(2)
It is also possible to apply column specific styles
也可以应用列特定样式
df.style.format({
'A': '{:,.1f}'.format,
'B': '{:,.3f}'.format,
})