从导入的文本文件中排序numpy列表

0 投票
1 回答
514 浏览
提问于 2025-04-17 17:12

在我之前的帖子中,我提到过如何对数据进行排序,现在我想弄清楚为什么我的numpy数组没有把从文件夹读取的新数据“添加”进去。之前的帖子解决了我按正确顺序读取文件的问题,但当我从每个文件读取数据并把它们放进numpy数组时,最终得到的数组却没有按照指定的顺序排列数据。

举个例子,我的文件是这样读取的:

0129A.txt

0201A.txt

0210A.txt

0215A.txt 

这些文件在代码中被正确读取(见下面的列表),但是最终的结果,我的数组(在代码中看到的)却没有按照正确的顺序包含每个文件的内容。

这是我的示例代码:

datadirectory = '/media/DATA'
os.chdir(datadirectory)
listing = sorted(os.listdir(datadirectory))
my_array = np.zeros(shape=(0,3))

for infile in glob.glob('*.txt'):
    dataset = open(infile).readlines()
    data = np.genfromtxt(dataset, usecols=(0,1,2))
    lta = data
    my_array = np.vstack(my_array, lta)

我本来期待每次读取文件时,代码能创建一个三列的数组(就像文本文件中的数据),然后再移动到下一个文件(按照列表中的定义),并以相同的顺序添加数据——但实际上并没有这样做。

我漏掉了什么呢?

1 个回答

1

这段代码看起来不太像你的真实代码——有几个明显的拼写错误(比如 glob.blog)。请记得总是复制粘贴代码。

不过假设你运行的代码是用 glob.glob,那么你可能需要对结果进行排序,这样才能得到你想要的顺序:

for infile in sorted(glob.glob("*.txt")):
    # do stuff here

这个排序是按字母顺序来的(也就是“字典序”,所以“10”会排在“2”前面);如果你想要其他的排序方式,可以给 sorted 传递一个键函数。

演示:

~/coding/fill$ more *.txt
::::::::::::::
0129A.txt
::::::::::::::
1 2 3
1 2 3
1 2 3
::::::::::::::
0201A.txt
::::::::::::::
4 5 6
4 5 6
4 5 6

::::::::::::::
0210A.txt
::::::::::::::
7 8 9
7 8 9

::::::::::::::
0215A.txt
::::::::::::::
10 11 12
10 11 12
10 11 12

还有

import os, glob
import numpy as np

datadirectory = '.'
os.chdir(datadirectory)
listing = sorted(os.listdir(datadirectory))
my_array = np.zeros(shape=(0,3))

for infile in sorted(glob.glob('*.txt')):
    dataset = open(infile).readlines()
    data = np.genfromtxt(dataset, usecols=(0,1,2))
    lta = data
    my_array = np.vstack([my_array, lta])

print my_array

给我返回

[[  1.   2.   3.]
 [  1.   2.   3.]
 [  1.   2.   3.]
 [  4.   5.   6.]
 [  4.   5.   6.]
 [  4.   5.   6.]
 [  7.   8.   9.]
 [  7.   8.   9.]
 [ 10.  11.  12.]
 [ 10.  11.  12.]
 [ 10.  11.  12.]]

撰写回答