pandas 将熊猫浮点系列转换为 int
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34145190/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
convert pandas float series to int
提问by Christopher
I am discretizing my series for a learner. I really need the series to be in float, and I reallyneed to avoid for loops.
我正在为学习者离散化我的系列。我真的需要这个系列是浮动的,我真的需要避免 for 循环。
How do I convert this series from float to int?
如何将这个系列从 float 转换为 int?
Here is my function that is currently failing:
这是我目前失败的功能:
def discretize_series(s,count,normalized=True):
def discretize(value,bucket_size):
return value % bucket_size
if normalized:
maximum = 1.0
else:
minimum = np.min(s)
s = s[:] - minimum
maximum = np.max(s)
bucket_size = maximum / float(count)
Here is the line that causes the function to fail:
这是导致函数失败的行:
s = int((s[:] - s[:] % bucket_size)/bucket_size)
The int() induces a casting error: I am unable to cast the pandas series as an int series.
int() 会导致转换错误:我无法将 pandas 系列转换为 int 系列。
return s
If I remove the int(), the function works, so I may just see if I can get it to work anyway.
如果我删除 int(),该函数就可以工作,所以我可能只是看看我是否可以让它工作。
回答by Andras Deak
The regular python int
function only works for scalars. You should either use a numpy function to round the data, either
常规 pythonint
函数仅适用于标量。您应该使用 numpy 函数来舍入数据,或者
s = np.round((s - s % bucket_size) / bucket_size) #to round properly; or
s = np.fix((s - s % bucket_size) / bucket_size) #to round towards 0
and if you actually want to convert to an integer type, use
如果您确实想转换为整数类型,请使用
s = s.astype(int)
to cast your array.
投射你的数组。