Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding index to numpy arrays

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]]
like image 652
VeilEclipse Avatar asked Mar 23 '15 11:03

VeilEclipse


People also ask

Can you index a NumPy array?

Array indexing is the same as accessing an array element. You can access an array element by referring to its index number. The indexes in NumPy arrays start with 0, meaning that the first element has index 0, and the second has index 1 etc.

How do you add an index to an array in Python?

By using append() function : It adds the elements to the end of the array. By using insert() function : It adds elements at the given index in an array.

Can you use index for array?

To use values returned as an array, enter the INDEX function as an array formula. Note: If you have a current version of Microsoft 365, then you can input the formula in the top-left-cell of the output range, then press ENTER to confirm the formula as a dynamic array formula.

How do I add an element to an array in NumPy?

For this task we can use numpy. append(). This function can help us to append a single value as well as multiple values at the end of the array.


1 Answers

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
like image 121
Carsten Avatar answered Oct 16 '22 11:10

Carsten