【问题标题】:numpy.delete changing arrays of floats to stringsnumpy.delete 将浮点数数组更改为字符串
【发布时间】:2014-05-17 02:46:25
【问题描述】:

我正在使用numpy.delete 函数从多个数组中删除元素。我从这个问题开始Make this simple for/if block more pythonic 并在应用那里给出的答案后到达:

# Data lists.
a = [3,4,5,12,6,8,78,5,6]
b = [6,4,1.,2,8,784.,43,6.,2]
c = [8,4.,32.,6,1,7,2.,9,23]

# Maximum limit.
max_limit = 20.

# Store indexes of elements to be removed.
indexes = [i for i, t in enumerate(zip(b, c)) if any(e > max_limit for e in t)]

# Remove elements from all lists.
big_array = np.array([a, b, c])
clean_array = np.delete(big_array, indexes, axis=1)

# Final clean lists.
a_clean, b_clean, c_clean = clean_array

我遇到的问题是我的一个列表实际上是由 strings 而不是浮点数组成的,如下所示:

# Data lists.
a = ['a','b','c','d','e','f','g','h','i'] # <-- strings
b = [6,4,1.,2,8,784.,43,6.,2] # <-- floats
c = [8,4.,32.,6,1,7,2.,9,23] # <-- floats

当我在numpy.delete 行上方应用代码时,会将所有最终列表 (a_clean, b_clean, c_clean) 中的所有元素转换为字符串,而不是将第一个元素保留为字符串,其余元素保留为浮点数.

如果无法解决,我该如何防止这种情况发生或解决?

【问题讨论】:

    标签: python arrays string numpy


    【解决方案1】:

    如果您要使用 numpy,最好将列表转换为数组。它看起来像:

    a = np.array(a)
    b = np.array(b)
    c = np.array(c)
    
    mask = (b > max_limit) | (c > max_limit)
    
    a = a[mask]
    b = b[mask]
    c = c[mask]
    
    >>> a
    array(['c', 'f', 'g', 'i'],
          dtype='|S1')
    >>> b
    array([   1.,  784.,   43.,    2.])
    >>> c
    array([ 32.,   7.,   2.,  23.])
    

    【讨论】:

      猜你喜欢
      • 2014-07-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-08
      • 1970-01-01
      • 1970-01-01
      • 2019-01-07
      • 1970-01-01
      相关资源
      最近更新 更多