我正在使用 python 2.7.9 进行编程。我需要为变量分配一个值范围。
示例:我需要变量“x”来获取 0 到 10 之间的数字(0 > x < 10)( Including decimals) so that I can compare this variable with another
您可以使用 range 或 xrange。
让我向您展示它是如何工作的。如果你写
x = range(5)
它会给你一个包含元素 [0, 1, 2, 3, 4] 的列表,默认起点是 0,终点是 n-1。
如果你希望列表为0
x = range(1, 10) # here Default start is 1 and end is less than 10
如果您有任何其他疑问,请告诉我。
有几种方法可以做到这一点:
最明显的是使用
range(1,10)
>>>> range_list = [i for i in range(1,10)]
了解更多信息:http://pythoncentral.io/pythons-range-function-explained/
给定的列表也可以使用 numpy 生成:
>>> np.linspace(1,9,9)
array([ 1., 2., 3., 4., 5., 6., 7., 8., 9.])
更多信息:https://docs.scipy.org/doc/numpy/reference/ generated/numpy.linspace.html
我认为您要问的是对数据进行分箱。 您可以使用剪切方法来做到这一点。
interval_range = pd.interval_range(start=0, freq=10, end=280)
df['target_range'] = pd.cut(df['total_runs'], bins=interval_range)