使用python生成1d数组形式的txt文件

2024-04-27 21:09:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我是新来的python.为我的拼贴项目中需要开发一些程序,为了数据分析我使用了大量的数组,这些数组的值都取自文本文件中的txt文件,下面给出了这些值

0
0
0
0,0,0
0,0,0,0,0,0
0,0
0,0,0

我想转换成一维数组,比如 [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]

我是怎么做到的。谢谢

我得到一些帮助完整的代码,但这不工作,我得到一些错误,我不能识别

path2='page_2.txt'
input2 = np.array(np.loadtxt(path2, dtype='i', delimiter=','))

错误:

ValueError                                Traceback (most recent call
last) <ipython-input-139-8836e57e833d> in <module>
      5 
      6 path2='page_2.txt'
----> 7 input2 = np.array(np.loadtxt(path2, dtype='i', delimiter=','))
      8 
      9 path3='page_4.txt'

~\Anaconda3\lib\site-packages\numpy\lib\npyio.py in loadtxt(fname,
dtype, comments, delimiter, converters, skiprows, usecols, unpack,
ndmin, encoding)    1099         # converting the data    1100        
X = None
-> 1101 for x in read_data(_loadtxt_chunksize):1102 if X is None:1103 X = np.array(x, dtype) 
~\Anaconda3\lib\site-packages\numpy\lib\npyio.py in
read_data(chunk_size)    1023                 line_num = i + skiprows
+ 1 1024 raise ValueError("Wrong number of columns at line %d"
-> 1025 % line_num)1026 1027# Convert each value according to its column and store

ValueError: Wrong number of columns at line 4


Tags: intxtdatalib错误nplinepage
2条回答

这是因为第4行(即0,0,0)有三列,而不是前三行。你知道吗

相反,您可以将所有行串联起来并将其转换为一个数组:

with open(path2) as f:
    str_arr = ','.join([l.strip() for l in f])

int_arr = np.asarray(str_arr.split(','), dtype=int)

print(int_arr)
[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]

如果我理解正确,您希望整个文件中的所有元素都在一个数组中。你知道吗

可以这样做:

with open(filename) as f:
    numbers = [
        e
        for line in f
        for e in line.strip().split(',')]

int_arr = np.asarray(numbers, dtype=int)

之后我们有:

>>> print(int_arr)
array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])

相关问题 更多 >