np.array2string不删除数组周围的括号 [英] np.array2string not removing brackets around an array

查看:105
本文介绍了np.array2string不删除数组周围的括号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试从excel文件中提取数据,将其转换为数组,然后将其写入其他当前未定义的文件类型(因此,.txt文件是当前的占位符文件类型).我确定代码相当丑陋,但是可以正常工作:

I have been attempting to extract data from excel files, convert it into an array, then write it into some other currently undefined file type (so a .txt file is the current placeholder file type). I'm sure the code is rather ugly, but it works:

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文件,但是并没有删除括号.输出看起来像这样(生成了随机数作为测试):

Anyway, the problem I am running into is that, while it does print to the .txt file, the brackets are not removed. The output looks as such (with random numbers generated as a test):

 [ 20   6]
 [ 76   2]
 [ 93  97]
 [ 29  75]
 [ 75  69]
 [ 77  81]
 [ 19  51]
 [ 70 100]
 [ 94  68]

我想去掉括号,但是似乎没有任何一行方法可以做到这一点.任何帮助将不胜感激.

I would like to remove the brackets, but there don't seem to be any one line methods to do this. Any help would be appreciated.

推荐答案

array2string 格式化要显示的数组,就像执行 print 一样:

array2string formats the array for display, same as if you were to do a 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]]'

请注意,列表的打印字符串还包括方括号(和逗号):

Note that the print string of a list also includes the brackets (and commas):

In [35]: str(x.tolist())
Out[35]: '[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11]]'

array2string 的另一个复杂之处在于,它对长数组使用省略号缩写(尽管可以通过参数更改).

Another complication with array2string is that it uses the ellipsis abbreviation for long arrays (though that can be changed with a parameter).

np.savetxt 是将2d数组写入文件的相对简单的操作,并且可以使用显式格式进行仿真.

np.savetxt is a relatively simple write of a 2d array to a file, and can be emulated with explicit formatting.

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'

这篇关于np.array2string不删除数组周围的括号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆