我已经收到了一份电子表格,其中包含了一系列人员及其教育程度,我已将其读入DataFrame。
我正在尝试返回一个字典,其中包含已经四舍五入到小数点后3位的相对频率。
BA/BS 0.458
Some Col 0.250
PostGrad 0.167
High Sch 0.125
Name: education, dtype: float64
返回
return self.data['education'].value_counts(normalize=True).round(3).to_dict()
但
{u'High Sch': 0.125, u'BA/BS': 0.45800000000000002, u'PostGrad': 0.16700000000000001, u'Some Col': 0.25}
返回
def inputLandValue():
while(1):
try:
value=int(input('Please enter the value of the property '))
break
except:
print('Please enter a whole number (10000)')
return value
def main():
while(1):
landValue = inputLandValue()
print(landValue)
doMoreStuff = input('Do you want to continue? y/n ')
if(doMoreStuff.lower() != 'y'):
break
main()
input()
我真的对此感到茫然。任何人都可以对正在发生的事情有所了解吗?
答案 0 :(得分:1)
试试这个:
pd.options.display.float_format = '{:,.3f}'.format
答案 1 :(得分:0)
np.round没有按照你的想法做到。
例如运行:
np.round(3.1231,3)
返回
3.1230000000000002
np.round正在转换为舍入数字(3.123)的最近可能表示,并且它可以用它具有的精度做的最接近的表示是您在上面看到的数字(3.1230000000000002)
您在示例中看到的是,当您调用对象时
return self.data['education'].value_counts(normalize=True).round(3)
pd.Series正在对输出执行一些修剪。
my_s = pd.Series([3.123,2], index=['a','b'])
my_s
打印
a 3.123
b 2.000
dtype: float64
但my_s [a]打印
3.1230000000000002
您要做的是按照其他答案建议的方式格式化数字的表示形式。
答案 2 :(得分:0)
MaxU的响应适用于打印,但在使用to_dict
时不会更改任何内容。
这是我用来解决这个问题的方法:
my_s = pd.Series([0.12345,0.45678], index=['a','b'])
my_s = my_s.apply(lambda x: '{:,.3%}'.format(x))
这给出了:
my_s.to_dict()
{'b': '45.678%', 'a': '12.345%'}