社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

使用python生成1d数组表单txt文件

Toufik Khan • 5 年前 • 1762 次点击  

我是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 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

值错误:第4行的列数错误

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/54633
 
1762 次点击  
文章 [ 2 ]  |  最新文章 5 年前
Ralf
Reply   •   1 楼
Ralf    6 年前

如果我理解正确,您需要将整个文件中的所有元素放在一个数组中。

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])
Chris
Reply   •   2 楼
Chris    6 年前

因为第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]