gpt4 book ai didi

python - NumPy 的 python : Sorting columns of an array in alphabetical order

转载 作者:太空宇宙 更新时间:2023-11-04 05:19:18 24 4
gpt4 key购买 nike

我目前正在使用 Python 3 和 Numpy。我有一个使用 numpy.genfromtxt("textfile.txt", names=True) 创建的结构化数组,我想按字母顺序对列进行排序。

  • 第一行包含列的名称。

  • 其他列包含每个实例的伴随值。

我只想将列的顺序切换为列名的字母顺序。例如,现在列的顺序是 'year''population''area' 我希望它变成 '面积','人口','年份'。在此先感谢您的帮助!

最佳答案

对于下面的numpy数组,答案是:

import numpy as np


x = np.array([(2015, 34, 12, 13), (2016, 41, 6, 7), (2016, 17, 5, 2),
(2013, 21, 8, 19), (2013, 1, 81, 9)],
dtype=[('year', '<i8'), ('tigers', '<i8'), ('monkeys', '<i8'), ('cows', '<i8')])

x[numpy.sort(x.dtype.names)]

# Output:
array([(13, 12, 34, 2015), (7, 6, 41, 2016), (2, 5, 17, 2016),
(19, 8, 21, 2013), (9, 81, 1, 2013)],
dtype=[('cows', '<i8'), ('monkeys', '<i8'), ('tigers', '<i8'), ('year', '<i8')])

关于python - NumPy 的 python : Sorting columns of an array in alphabetical order,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40846082/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com