0

data有了这个称为...的DataFrame

                    winner
 runner_name                         
 Steve                   0
 Joe                     0
 Marsha                  1
 Kent                    0

如果我创建一个占位符为 0 的新列...

 data['weighted'] = 0

当我传递一个十进制值以循环更新它时(经过一长串的计算和其他东西)......

 data.ix[runner_name]['weighted'] = 45.88

...它会自动将数字四舍五入。因此,框架变成..

                    winner  weighted
 runner_name                         
 Steve                   0        46
 Joe                     0        80
 Marsha                  1       100
 Kent                    0        80

如何防止它四舍五入?

4

1 回答 1

2

分配一个浮点数会导致 Pandas 给列一个floatdtype:

data['weighted'] = 0.0

import pandas as pd
data = pd.DataFrame({'winner':[0,0,1,0]}, index=pd.Series(['Steve', 'Joe', 'Marsha', 'Kent'], name='runner_name'), )
data['weighted'] = 0.0
data.ix['Steve', 'weighted'] = 45.88
print(data)

产量

             winner  weighted
runner_name                  
Steve             0     45.88
Joe               0      0.00
Marsha            1      0.00
Kent              0      0.00

>>> print(data.dtypes)
winner        int64
weighted    float64
dtype: object
于 2013-08-12T12:50:49.540 回答