簡體   English   中英

Python從文件的列中讀取由空格分隔的數組

[英]Python read arrays delimited by white space from columns in a file

我有一個具有以下結構的文件:

1
2
3

23
33
55

1
2
4

...

等等。 所以我想將數據提取到多維數組,即[[1,2,3], [23,33,55], [1,2,4]...] 到目前為止,我已經嘗試使用numpy.loadtxt()函數,但是我得到了包含所有數字的一維數組,並且還嘗試了以下代碼段:

data_tot = []
with open('file.txt', 'r') as infile:
     for line in infile:
         if line.rstrip() != '':
            data = []
            data.append(line.rstrip())
         else:
            data_tot.append(data)

其中data_tot是我想要的數組,但是我得到了類似data_tot = [[1], [23], [1] ...]

關於如何解決此問題的任何想法。 提前致謝。

在您提供的代碼段中,每當行不為空時,都會清除data列表。

data_buf = []
data_tot = []
with open('file.txt', 'r') as infile:
     for line in infile:
         if line.rstrip() == '':
            data_tot.append(data_buf[:])
            data_buf = []
         else:
            data_buf.append(line.rstrip())
if len(data_buf) > 0:
    data_tot.append(data_buf[:])

請注意,data_buf [:]復制列表對象以避免在下一次迭代中對其進行修改。 另外,如果最后一個緩沖區后面沒有空行,則應將其添加到總列表中。

這是帶有StringIO而不是文件的完整的獨立示例代碼

import io

f = io.StringIO("""1
2
3

23
33
55

1
2
4
""")
data_buf = []
data_tot = []
with f as infile:
     for line in infile:
         if line.rstrip() == '':
            data_tot.append(data_buf[:])
            data_buf = []
         else:
            data_buf.append(line.rstrip())
data_tot.append(data_buf[:])

您可以通過重塑來更改numpy數組的形狀

#reshape the array to 3 by n 
np.loadtxt("file.txt").reshape(-1,3)

隨身攜帶的數據應該可以:

[[  1.   2.   3.]
 [ 23.  33.  55.]
 [  1.   2.   4.]
 ...]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM