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]]
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With