Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

numpy.savetxt- Save one column as int and the rest as floats?

The Problem

So I have a 2D array (151 rows, 52 columns) I'd like to save as a text file using np.savetxt. However, I want the first column's numbers to save as integers (1950, 1951, etc) while the rest of the data saves as precision 5 (4 if rounded) floating point numbers (2.7419, 2.736, etc). I can't figure out how to do this.

The Code

When I print the first 4 rows & 3 columns of the output of the array, it looks like this.

[[ 1950. 2.7407 2.7396]

[ 1951. 2.7419 2.736 ]

[ 1952. 2.741 2.7374]

[ 1953. 2.7417 2.7325]]

When I use the following...

np.savetxt('array.txt',data,fmt="%1.4f")

The array saves the first column as a precision 5 floating point numbers like the rest of the data (1950.0000, 1951.0000, etc). When I try to specify different formats as such...

np.savetxt('array.txt',data,fmt="%i %1.4f")

I get the following error: "ValueError: fmt has wrong number of % formats: %i %1.4f"

The Question

Is there a way I say save the first column as integers and the rest of the columns as floating point numbers?

like image 621
ChristineB Avatar asked Oct 13 '16 20:10

ChristineB


2 Answers

data has 3 columns, so you need supply 3 '%format's. For example:

np.savetxt('array.txt', data, fmt='%i %1.4f %1.4f')

should work. If you have a lot more than 3 columns, you can try something like:

np.savetxt('array.txt', data, fmt=' '.join(['%i'] + ['%1.4f']*N))

where N is the number of columns needing float formatting.

like image 67
wflynny Avatar answered Sep 30 '22 19:09

wflynny


As @wflynny, but with out join:

np.savetxt('array.txt', data, fmt='%i'+' %1.4f'*N)
like image 32
Friedrich Avatar answered Sep 30 '22 19:09

Friedrich