arrays - np.array2string 不删除数组周围的括号
问题描述
我一直在尝试从 excel 文件中提取数据,将其转换为数组,然后将其写入其他一些当前未定义的文件类型(因此 .txt 文件是当前的占位符文件类型)。我确定代码相当难看,但它有效:
import os
import pandas as pd
import glob
import numpy as np
def xlxtract():
for filename in glob.glob('*.xlsx'):
ExcelFile = filename[:-5]
RosewoodData = pd.read_excel(ExcelFile + '.xlsx')
DataMatrix = np.array(RosewoodData)
DataMatrixString = np.array2string(DataMatrix, precision=4, separator=' ')
NewFile = open(ExcelFile + 'MATRIX.txt', 'w')
NewFile.write(' ' + DataMatrixString[1:-1])
NewFile.close()
print('Your file has been printed to ' + ExcelFile + '.txt')
无论如何,我遇到的问题是,虽然它确实打印到 .txt 文件,但括号没有被删除。输出如下所示(生成随机数作为测试):
[ 20 6]
[ 76 2]
[ 93 97]
[ 29 75]
[ 75 69]
[ 77 81]
[ 19 51]
[ 70 100]
[ 94 68]
我想删除括号,但似乎没有任何一种方法可以做到这一点。任何帮助,将不胜感激。
解决方案
array2string
格式化数组以进行显示,就像您要执行以下操作一样print
:
In [32]: x = np.arange(12).reshape(4,3)
In [33]: x
Out[33]:
array([[ 0, 1, 2],
[ 3, 4, 5],
[ 6, 7, 8],
[ 9, 10, 11]])
In [34]: np.array2string(x)
Out[34]: '[[ 0 1 2]\n [ 3 4 5]\n [ 6 7 8]\n [ 9 10 11]]'
请注意,列表的打印字符串还包括括号(和逗号):
In [35]: str(x.tolist())
Out[35]: '[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11]]'
另一个复杂array2string
之处是它使用省略号缩写表示长数组(尽管可以通过参数更改)。
np.savetxt
是将二维数组写入文件的相对简单的方法,可以使用显式格式进行模拟。
In [37]: np.savetxt('test.txt', x, fmt='%d', delimiter=',')
In [38]: cat test.txt # ipython system command to display a file
0,1,2
3,4,5
6,7,8
9,10,11
In [39]: for row in x:
...: print('%d,%d,%d'%tuple(row))
...:
0,1,2
3,4,5
6,7,8
9,10,11
或作为一个字符串
In [42]: astr = '\n'.join(['%3d %3d %3d'%tuple(row) for row in x])
In [43]: astr
Out[43]: ' 0 1 2\n 3 4 5\n 6 7 8\n 9 10 11'
推荐阅读
- javascript - 从客户端 javascript 将文件上传到 AWS
- c# - 如何在代码中设置按钮的内部属性?
- bash - awk 退出的意外行为
- jboss - 如何强制 wildfly-8.2.1.Final 从目录而不是战争加载 .class?
- html - 弹性项目应该获得所有其余的宽度
- java - 为什么我会收到 Velocity “Velocity 未正确初始化”这个错误?
- if-statement - 为什么这个 elsif 不起作用?[购物]
- windows - Windows 上 gstreamer 的 Ladspa 插件
- java - Maven force 包含其中没有 java 类的包
- sql - 每年年初获取有效订单