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
Answer from Carsten on Stack OverflowTrying to add 1 to the element at a certain index of a numpy array
arrays - How to add an element at the index using numpy in python - Stack Overflow
arrays - Adding elements to a specified index in python Numpy - Stack Overflow
python - Index of element in NumPy array - Stack Overflow
I’ve created some np.zeros arrays but I want to add 1 to some of the zeros at certain index’s. Does anyone know a way to do this as I currently can’t find anything anywhere. Or will I have to create a list full of 0s and then convert it to a np array once I have manipulated it the way I want? Would go from 0,0,0,0,0,0,0 To looking something like: 0,2,0,0,1,1,3
Any help appreciated.
Use np.insert
import numpy as np
np.insert(array, index, number)
You can use the numpy.insert function to insert a value at a specified point in a numpy.array. Here is how you would use it in your case:
array = np.array([ 31, 28, 31, 30, 31, 30, 31, 31])
np.insert(array, 5, 3)
The second argument is the index before which you wish to insert the value, which is the third argument. See the documentation here for more information, especially for higher-dimensional arrays, which can get a bit more complicated.
Use np.where to get the indices where a given condition is True.
Examples:
For a 2D np.ndarray called a:
i, j = np.where(a == value) # when comparing arrays of integers
i, j = np.where(np.isclose(a, value)) # when comparing floating-point arrays
For a 1D array:
i, = np.where(a == value) # integers
i, = np.where(np.isclose(a, value)) # floating-point
Note that this also works for conditions like >=, <=, != and so forth...
You can also create a subclass of np.ndarray with an index() method:
class myarray(np.ndarray):
def __new__(cls, *args, **kwargs):
return np.array(*args, **kwargs).view(myarray)
def index(self, value):
return np.where(self == value)
Testing:
a = myarray([1,2,3,4,4,4,5,6,4,4,4])
a.index(4)
#(array([ 3, 4, 5, 8, 9, 10]),)
You can convert a numpy array to list and get its index .
for example:
tmp = [1,2,3,4,5] #python list
a = numpy.array(tmp) #numpy array
i = list(a).index(2) # i will return index of 2, which is 1
this is just what you wanted.
You can just do df.index.values:
df = pd.DataFrame(index=['a', 'b', 'c'])
df.index.values
# array(['a', 'b', 'c'], dtype=object)
Try time = df1.as_matrix(columns=df1.columns[0:1]). It looks like columns should be a 1-dimensional array (well, actually, an Index), and giving two indices to a 1-dimensional array would give that error.