如果你有一個零d陣列像你的榜樣,那麼你可以這樣做:
b = np.array((1, 2.0, 'buckle_my_shoe'),
dtype=[('f0', '<i4'), ('f1', '<f8'), ('f2', 'S14')])
with open('myfile.dat','w') as f:
for el in b[()]:
f.write(str(el)+' ') # or `f.write(repr(el)+' ') to keep the quote marks
這是通過使用[()]
訪問0D數組的元素:
>>> b.ndim
0
>>> b[0]
IndexError: 0-d arrays cannot be indexed
>>> b[()]
(1, 2.0, 'buckle_my_shoe')
如果您定期使用零維的numpy陣列,爲了使複雜的dtype,我可能會建議NamedTuple
from collections
。
>>> import collections
>>> A = collections.namedtuple('A', ['id', 'val', 'phrase'])
>>> a = A(1, 2.0, 'buckle_my_shoe')
>>> a
A(id=1, val=2.0, phrase='buckle_my_shoe')
>>> a.id
1
>>> a.val
2.0
>>> a.phrase
'buckle_my_shoe'
with open('myfile.dat','w') as f:
for el in a:
f.write(repr(el)+' ')
如果陣列有一個以上的元素:
a = np.array([(1, 2.0, 'buckle_my_shoe'),
(3, 4.0, 'lock_the_door')],
dtype=('i4, f8, a14'))
我不知道究竟你希望你的文件是什麼樣子。如果你想用空格分開的元組,這是我認爲最好的辦法:這會導致像文件
with open('myfile.dat','w') as f:
for row in a:
f.write(repr(row)+' ')
:
(1, 2.0, 'buckle_my_shoe') (3, 4.0, 'lock_the_door')
也許你想有沒有逗號或圓括號在這種情況下,你可以這樣做:
with open('myfile.dat','w') as f:
for row in a:
for el in row:
f.write(str(el)+' ')
這給本文件:
1 2.0 buckle_my_shoe 3 4.0 lock_the_door
使用repr
保持qutoes周圍的字符串
with open('myfile.dat','w') as f:
for row in a:
for el in row:
f.write(repr(el)+' ')
這給本文件:
1 2.0 'buckle_my_shoe' 3 4.0 'lock_the_door'
獎勵:如果你的D型細胞具有字段名稱,你可以打印這些:
a.dtype.names = "index value phrase".split()
a.dtype
#dtype([('index', '<i4'), ('value', '<f8'), ('phrase', 'S14')])
with open('myfile.dat','w') as f:
for name in a.dtype.names:
f.write(name + ' ') # or write(repr(name)) to keep the quote marks
for row in a:
for el in row:
f.write(repr(el)+' ')
注意,如果你複製這些文件被警告我以前'w'
不'a'
,這樣我就可以覆蓋每一個在我的測試案例。
偉大的答案,但似乎沒有一個0-d陣工作。例如。 '[f.write(str(el))for a']給出了一個'TypeError:對一個0-d數組的迭代'。雖然工作良好,但> 1排。 – atomh33ls 2013-04-08 15:22:26
@ atomh33ls對不起,這是故意的,因爲我認爲0D數組是個錯誤。我修正了這個問題。 – askewchan 2013-04-08 15:51:14
@ atomh33ls注意我的建議是使用命名元組而不是0D numpy數組,如果你經常這樣做的話。 – askewchan 2013-04-08 15:53:30