【问题标题】:Creating a numpy array and then sorting array创建一个 numpy 数组,然后对数组进行排序
【发布时间】:2017-11-27 11:38:23
【问题描述】:

我遇到了一个似乎无法解决的问题,我需要获取一个字符串列表并计算一些值,然后将相关字符串和相关整数添加到一个 numpy 数组中。我被告知首先创建零的 numpy 数组,因为它的长度是已知的,所以我可以这样做。我的问题是如何迭代地将每个字符串添加到第一列(名称)和每个值(标签)到第二列,然后按第一列按字母顺序对整个数组进行排序

fileCount = sum([len(files) for r, d, files in os.walk(inputDirectory)])
labelArray = np.zeros(shape = (fileCount,2))
arrayInsertCounter = 0

for label, subDirectories in enumerate(inputDirectory):

  subDirPath = os.path.join(inputDirectory, subDirectories)

  for name in subDirPath:

    labelArray[arrayInsertCounter] = [name,label]
    arrayInsertCounter += 1

【问题讨论】:

  • 你为什么要使用 numpy 呢?看起来普通的 python 列表会容易得多。如果需要数组,最后将其转换为数组。
  • np.zeros 中使用Object dtype 对此类混合dtype 数据进行初始化。
  • @roganjosh 我必须稍后在我的代码中将它作为一个 numpy 数组输入,你认为我可以在这里将它排序为一个列表,然后稍后将它转换为一个 numpy 数组吗?
  • 你绝对可以做到。只需构建一个列表并将其转换为数组。以现在的方式使用 numpy 并没有带来任何速度优势,因为 for 循环,它在 Python 时间运行。不确定在 numpy 或 python 中为您的列表排序是否更快,您必须根据需要在排序之前/之后进行测试和转换。
  • 非常感谢您的帮助

标签: python arrays sorting numpy


【解决方案1】:

您可以在 numpy 中使用结构化数组进行操作

import numpy as np

labels = list(map(''.join, zip(*3*((chr(ord('a')+(19*i)%24) for i in range(24)),))))
numbers = np.arange(8)

dt = np.dtype([('label', object), ('value', int)])

table = np.empty((8,), dtype = dt)

table['label'] = labels
table['value'] = numbers

print(table)
table.sort()
print(table)

输出:

#[('ato', 0) ('jex', 1) ('sni', 2) ('dwr', 3) ('mhc', 4) ('vql', 5)
# ('gbu', 6) ('pkf', 7)]
#[('ato', 0) ('dwr', 3) ('gbu', 6) ('jex', 1) ('mhc', 4) ('pkf', 7)
# ('sni', 2) ('vql', 5)]

编辑:如何访问个人记录:

table[2] = 'new label', 1000
table
# array([('ato',    0), ('dwr',    3), ('new label', 1000), ('jex',    1),
#        ('mhc',    4), ('pkf',    7), ('sni',    2), ('vql',    5)],
#       dtype=[('label', 'O'), ('value', '<i8')])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多