1

我有 1,000 个元素的 numpy 数组,我想将其转换为字符串。

我试过了:

map(str, a)

它很慢。还有其他选择吗?谢谢。

4

1 回答 1

2

如果要将 numpy 数组写入文本文件,请使用numpy.savetxt. 根据您的评论,这就是您想要的。

但是,为了回答您的原始问题,如果您可以使用固定长度的字符串,则有更快的方法将 numpy 数组转换为字符串。

对于简单的事情,您可以将其转换为固定长度的字符串数组。

例如

import numpy as np

# Generate some random floating-point data
x = np.random.random(100)

# Convert it to fixed-length strings with a maximum length of 5 characters
y = x.astype('|S5')

print 'Original Array'
print x
print 'Converted to fixed-length strings'
print y

这输出:

Original Array
[ 0.25669986  0.55193955  0.39582629  0.40559555  0.75836284  0.13031881
  0.84448005  0.20825593  0.32131777  0.5738351   0.72200185  0.14700912
  0.62306299  0.21549908  0.96927738  0.13327512  0.06948689  0.34436446
  0.58785565  0.58557563  0.3229981   0.0356056   0.67621536  0.07334146
  0.25804432  0.59477881  0.10382583  0.47255438  0.0747982   0.41586059
  0.54310507  0.68426668  0.14454108  0.62950246  0.30748958  0.56605352
  0.25072476  0.70945076  0.72311872  0.2357644   0.59668047  0.27536644
  0.96557189  0.97749755  0.95629738  0.15902741  0.32879056  0.60324024
  0.07463531  0.77562818  0.20181969  0.53088481  0.85723283  0.25163771
  0.06770161  0.45302361  0.3500556   0.37980214  0.87567327  0.94278158
  0.28586752  0.35682239  0.8746877   0.99562283  0.38323688  0.90561641
  0.64439454  0.53465359  0.37486244  0.33196021  0.99762377  0.29295412
  0.50162051  0.17312773  0.80100872  0.04233855  0.69062118  0.59194923
  0.65409137  0.25636784  0.40616824  0.82858658  0.90618301  0.87036914
  0.37534268  0.566982    0.55454063  0.75048023  0.56582157  0.62779239
  0.05196828  0.86418784  0.9862007   0.43015164  0.43576519  0.64918536
  0.99522735  0.81158283  0.02115479  0.47745413]
Converted to fixed-length strings
['0.256' '0.551' '0.395' '0.405' '0.758' '0.130' '0.844' '0.208' '0.321'
 '0.573' '0.722' '0.147' '0.623' '0.215' '0.969' '0.133' '0.069' '0.344'
 '0.587' '0.585' '0.322' '0.035' '0.676' '0.073' '0.258' '0.594' '0.103'
 '0.472' '0.074' '0.415' '0.543' '0.684' '0.144' '0.629' '0.307' '0.566'
 '0.250' '0.709' '0.723' '0.235' '0.596' '0.275' '0.965' '0.977' '0.956'
 '0.159' '0.328' '0.603' '0.074' '0.775' '0.201' '0.530' '0.857' '0.251'
 '0.067' '0.453' '0.350' '0.379' '0.875' '0.942' '0.285' '0.356' '0.874'
 '0.995' '0.383' '0.905' '0.644' '0.534' '0.374' '0.331' '0.997' '0.292'
 '0.501' '0.173' '0.801' '0.042' '0.690' '0.591' '0.654' '0.256' '0.406'
 '0.828' '0.906' '0.870' '0.375' '0.566' '0.554' '0.750' '0.565' '0.627'
 '0.051' '0.864' '0.986' '0.430' '0.435' '0.649' '0.995' '0.811' '0.021'
 '0.477']

这会快得多,但您仅限于固定长度的字符串。(显然,您可以更改长度。只需使用x.astype('|S10')或任何您想要的长度。)

但是,如果您只是想将数据写入文件,请再次使用savetxt.

于 2012-11-16T18:02:26.010 回答