5

I have a numpy array as:

prob_rf = [[0.4, 0.4, 0.4], 
           [0.5, 0.5, 0.5], 
           [0.6, 0.6, 0.6]]

I want to add an index number to each of the inner arrays as:

prob_rf = [[1, 0.4, 0.4, 0.4],
           [2, 0.5, 0.5, 0.5],
           [3, 0.6, 0.6, 0.6]]

and then save this array into a csv file using numpy.savetxt.

I am currently doing this as:

    id = [i for i in xrange(1,len(prob)+1)]
    prob_rf = np.insert(prob_rf, 0, id, axis=1)
    np.savetxt("foo.csv", prob_rf, delimiter=",", fmt='%1.1f')

But this is giving the output as

[[1.0, 0.4, 0.4, 0.4], 
 [2.0, 0.5, 0.5, 0.5], 
 [3.0, 0.6, 0.6, 0.6]]

Could someone please tell me how do I get the output as

[[1, 0.4, 0.4, 0.4], 
 [2, 0.5, 0.5, 0.5], 
 [3, 0.6, 0.6, 0.6]]
2
  • Why are you telling numpy to format everything with fmt='%1.1f' if that's not what you want? Commented Mar 23, 2015 at 11:13
  • It's because I want them in the format [0.4, 0.4, 0.4] else np.savetext saves as [4.00E-01, 4.00E-01, 4.00E-01] which I don't want. Commented Mar 23, 2015 at 11:18

1 Answer 1

7

Use a list with the fmt parameter to specify the formatting for each column:

fmt=['%d', '%1.1f', '%1.1f', '%1.1f']

Complete example:

import numpy as np
prob_rf = [[1, 0.4, 0.4, 0.4],
           [2, 0.5, 0.5, 0.5],
           [3, 0.6, 0.6, 0.6]]
np.savetxt("foo.csv", prob_rf, delimiter=",", fmt=['%d', '%1.1f', '%1.1f', '%1.1f'])

The resulting file:

1,0.4,0.4,0.4
2,0.5,0.5,0.5
3,0.6,0.6,0.6
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.