这可行,p_table.apply(pd.Series.round)但它没有小数位
import pandas as pd
Series.round(decimals=0, out=None)
Run Code Online (Sandbox Code Playgroud)
我试过这个,p_table.apply(pd.Series.round(2))但得到这个错误:
unbound method round() must be called with Series instance as first argument (got int instance instead)
Run Code Online (Sandbox Code Playgroud)
如何将数据框中的所有元素舍入到两位小数?
[编辑]想出来了.
import numpy as np
np.round(p_table, decimals=2)
Run Code Online (Sandbox Code Playgroud) 我有两列带有数字数据的熊猫表(dtype flaot64)。我已经将每列四舍五入到小数点后有 2 位数字,然后使用函数将其四舍五入到接近 0.5,但由于某种原因,只有一列四舍五入为 0.05,第二列四舍五入但错过了第二位数字。
这是一个假的例子,它可以工作并显示流程:
table=pd.DataFrame({'A': [0.62435, 0.542345,0.213452],
'B': [0.22426,0.15779,0.30346]})
#function for round to near 0.5:
def custom_round(x, base=5):
return base * round(float(x)/base)
table['A'] = table['A'].astype(float).round(2).apply(lambda x: custom_round(x, base=.05))
table['B'] = table['B'].astype(float).round(2).apply(lambda x: custom_round(x, base=.05))
table
>>>
A B
0 0.60 0.20
1 0.55 0.15
2 0.20 0.30
Run Code Online (Sandbox Code Playgroud)
但在我的桌子上,我最终得到了:
当我在没有函数的情况下运行脚本接近 0.5 时,我仍然得到两位数:
table['B'] = table['B'].round(2)
Run Code Online (Sandbox Code Playgroud)
我的问题是为什么会这样?以及如何修复它以便将两列四舍五入为 0.05 并显示两个数字?
编辑:有人问我如何将它应用到我的真实桌子上,所以:
df['A'] = df['A'].astype(float).round(2).apply(lambda x: custom_round(x, base=.05))
df['B']= df['B'].round(2).apply(lambda x: custom_round(x, base=.05))
Run Code Online (Sandbox Code Playgroud)