在pandas数据帧中舍入一列

Wes*_*ssi 2 python python-3.x pandas python-3.5

我有一个df像这样的pandas数据框:

          no_obs  price_cleaning  house_size
0         1             585          30
1         1             585          40
2         1             585          43
3         1             650          43
4         1             633          44
5         1             650          45
6         2             585          50
7         1             633          50
8         1             650          50
9         2             750          50 
Run Code Online (Sandbox Code Playgroud)

我想price_cleaning用这个函数对列中的值进行舍入:

def roundup(x): return int(math.ceil(x / 10.0)) * 10

我已经尝试了这个答案的解决方案(按功能将功能应用于Pandas数据帧):

cols = [col for col in df.columns if col != 'price_cleaning'] df[cols] = df[cols].apply(roundup)

我收到以下错误:TypeError :("无法将系列转换为",'发生在索引no_obs')

任何人都可以帮助我理解为什么这不起作用?如何将舍入功能应用于列?任何帮助深表感谢.

Zer*_*ero 6

我会像矢量化一样

In [298]: df['p'] = (np.ceil(df.price_cleaning / 10) * 10).astype(int)

In [299]: df
Out[299]:
   no_obs  price_cleaning  house_size    p
0       1             585          30  590
1       1             585          40  590
2       1             585          43  590
3       1             650          43  650
4       1             633          44  640
5       1             650          45  650
6       2             585          50  590
7       1             633          50  640
8       1             650          50  650
9       2             750          50  750
Run Code Online (Sandbox Code Playgroud)

对于10K行,时序 - 矢量化方法快〜15倍 apply

In [331]: %timeit (np.ceil(dff.price_cleaning / 10) * 10).astype(int)
1000 loops, best of 3: 436 µs per loop

In [332]: %timeit dff['price_cleaning'].apply(roundup)
100 loops, best of 3: 7.86 ms per loop

In [333]: dff.shape
Out[333]: (10000, 4)
Run Code Online (Sandbox Code Playgroud)

至少在这种情况下,性能差距越大,行数越多.