www.pieronigro.de
www.pieronigro.de

Reputation: 880

strings and arrays(matrix) row wise: numpy.savetxt

I have two string-arrays that have to follow each other row-wise and afterwards they have to be written in a text file

import numpy as np
title1 = np.array(['text1'])  
title2 = np.array(['text2'])
np.savetxt('result.csv',(title1, title2),fmt="%s")

result should be a file starting with:

text1
text2

but it´s more like this:

text1text2

the second problem is below these two rows of text I need to put a matrix (mine is much bigger) in the next row('s). The entries of the matrix should be spaced with a semicolon ";" - at the end of row there shouldn't be one(!)

a=np.array([[1.2,2.3,3.4],[4.5,5.6,6.7],[7.8,8.8,9.8]])
np.savetxt('test.csv', a, delimiter=';', fmt='%.1f')

resulting file should look like this:

text1
text2
1.2;2.3;3.4
4.5;5.6;6.7
7.8;8.8;9.8

the above code does not put the next rows of entries to the next row in my output file. (when opening it with notepad it does not, in excel it seems to work. How can I combine strings and numbers in my output in the way I described?

Upvotes: 3

Views: 9410

Answers (2)

www.pieronigro.de
www.pieronigro.de

Reputation: 880

i had the idea looking at another thread:

np.savetxt('test.csv',(title1, title2),fmt="%s", newline='\r\n')

import csv
with open('test.csv', 'a') as f:
    np.savetxt(f, I, delimiter=';', fmt='%s,'newline='\r\n')
f.close()

the 'a' is for the append- mode, but unfortunately i get an error message

line 1047, in savetxt
    fh.write(asbytes(format % tuple(row) + newline))
TypeError: must be str, not bytes

when i use 'ab' instead of 'a' i get a result that looks right in notepad but now in excel the first 2 columns of the matrix have "date" mode ...i look for clarification here to understand what happened?

Upvotes: 4

kazagistar
kazagistar

Reputation: 1597

Check out this answer. Numpy is encoding according to the unix standard, but notepad does not understand and expects windows only, and does not render \n without a \r, but almost any other non-braindead software will read it correctly.

EDIT: As explained in this other question or in the documentation, numpy.savetxt has a parameter that lets you set the newline encoding for windows. So, if you really want to be compatible with notepad, you want something like:

np.savetxt('test.csv', a, delimiter=';', newline='\r\n', fmt='%.1f')

Upvotes: 1

Related Questions