简体   繁体   English

如何从数字列表中创建数字符号的列表/数组

[英]how to create a list/array of number's signs from a list of numbers

I have a numpy array of numbers: 我有一大堆数字:

n =  [ 1.2,0,-0.5,0.3,0,-0.8]

I want to create a numpy array using the above that only holds the sign of the numbers, result should be: 我想创建一个numpy数组使用上面只保存数字的符号,结果应该是:

s = [1,0,-1,1,0,-1]

I can create this with a loop: 我可以用循环创建它:

s= np.zeros(n.shape[0])    
for i in range (n.shape[0]):
    if n[i]>0: s[i]=1
    if n[i]<0: s[i]=-1    

Is there a way to use list comprehension with numpy arrays that can do the same with high performance? 有没有办法使用列表理解与numpy数组,可以做同样的高性能?

If you are using numpy, a better solution is to use numpy.sign(): 如果你使用numpy,更好的解决方案是使用numpy.sign():

import numpy as np
s = np.sign(n)

This will give you a numpy array. 这会给你一个numpy数组。

array([ 1., 0., -1., 1., 0., -1.]) 数组([1.,0.,-1。,1.,0.,-1。])

To convert this floating point result to int, you may use: 要将此浮点结果转换为int,您可以使用:

s.astype(np.int)

If you want to convert it back to python list: 如果要将其转换回python列表:

s_list = s.tolist()

You can do the above in one line as: 您可以在一行中执行以上操作:

s = np.sign(n).astype(np.int).tolist()

The np.sign answer seems the best way, but if you want to code something, I feel like this should be pretty quick: np.sign答案似乎是最好的方法,但如果你想编写一些东西,我觉得这应该很快:

import numpy as np

def get_signs(array_of_numbers):
    f = lambda x: x and (1, -1)[x < 0]
    return np.fromiter((f(item) for item in array_of_numbers), array_of_numbers.dtype)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM