use*_*097 6 python rounding dataframe pandas
我有一个包含一列float64值的Pandas数据帧:
tempDF = pd.DataFrame({ 'id': [12,12,12,12,45,45,45,51,51,51,51,51,51,76,76,76,91,91,91,91],
'measure': [3.2,4.2,6.8,5.6,3.1,4.8,8.8,3.0,1.9,2.1,2.4,3.5,4.2,5.2,4.3,3.6,5.2,7.1,6.5,7.3]})
Run Code Online (Sandbox Code Playgroud)
我想创建一个只包含整数部分的新列.我的第一个想法是使用.astype(int):
tempDF['int_measure'] = tempDF['measure'].astype(int)
Run Code Online (Sandbox Code Playgroud)
这工作正常,但作为一个额外的复杂,我有一列缺少值:
tempDF.ix[10,'measure'] = np.nan
Run Code Online (Sandbox Code Playgroud)
此缺失值导致.astype(int)方法失败:
ValueError: Cannot convert NA to integer
Run Code Online (Sandbox Code Playgroud)
我以为我可以在数据列中舍入浮点数.但是,.round(0)函数将舍入到最接近的整数(更高或更低)而不是向下舍入.我找不到一个等效于".floor()"的函数,它将作用于Pandas数据帧的一列.
有什么建议?
你可以申请numpy.floor;
import numpy as np
tempDF['int_measure'] = tempDF['measure'].apply(np.floor)
id measure int_measure
0 12 3.2 3
1 12 4.2 4
2 12 6.8 6
...
9 51 2.1 2
10 51 NaN NaN
11 51 3.5 3
...
19 91 7.3 7
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13366 次 |
| 最近记录: |