linspace()生成一个浮点值,但是int是必需的

时间:2017-11-19 08:22:29

标签: python-2.7 dictionary

我正在生成x轴值,时间形式为1到23,v值是多个客户端。我希望将这两个列表作为字典加入,但是我使用linspace()生成了x的浮点值。

time_values = np.linspace(1,23,23) # print from 1,2...23
number_of_clients = [] # create empty list that will hold number of clients
        for i in range(1,24,1):
            rand_value =  random.randint(1,20) # generate number of clients
            number_of_clients.append(rand_value)


    data = dict(zip(time_values,number_of_clients))
    print data

输出

{1.0:12,2.0:11,3.0:3,4.0:19,5.0:12,6.0:12,7.0:5,8.0:13,9.0:15,10.0:3,11.0:15,12.0: 20,13.0:5,14.0:3,15.0:18,16.0:12,17.0:5,18.0:6,19.0:8,20.0:16,21.0:19,22.0:1,23.0:16}

如何将1.0转换为1等等。我尝试了int(time_vlaues),但它没有效果

1 个答案:

答案 0 :(得分:1)

尝试使用astype方法将numpy float数组转换为int数组:

time_values = np.linspace(1,23,23) # print from 1,2...23
number_of_clients = [] # create empty list that will hold number of clients
for i in range(1,24,1):
    rand_value =  random.randint(1,20) # generate number of clients
    number_of_clients.append(rand_value)


data = dict(zip(time_values.astype(int),number_of_clients))
print(data)

time_values = np.linspace(1,23,23,dtype='int') # print from 1,2...23
number_of_clients = [] # create empty list that will hold number of clients
for i in range(1,24,1):
    rand_value =  random.randint(1,20) # generate number of clients
    number_of_clients.append(rand_value)


data = dict(zip(time_values,number_of_clients))
print(data)

输出:

{1: 17, 2: 6, 3: 8, 4: 3, 5: 12, 6: 11, 7: 18, 8: 1, 9: 8, 10: 1, 11: 17, 12: 2, 13: 5, 14: 6, 15: 1, 16: 8, 17: 19, 18: 2, 19: 13, 20: 15, 21: 16, 22: 17, 23: 14}