user6352340
user6352340

Reputation: 107

Save NumPy array / vector to CSV

I have some numeric numbers ( about 550,000) and I tried to save them in a CSV file. My values can only be 1 or 2. But it is saved as:

['2.000000000000000000e+00']
['1.000000000000000000e+00']
['2.000000000000000000e+00']
['2.000000000000000000e+00']
...

My code is:

import numpy as np

def save_in_scv_format(My_Labels):
    K = []
    for i in range(len(My_Labels)):
        K.append(My_Labels[i])

    np.savetxt('My_labels.csv', K, delimiter = ',')

My_labels is a vector having integer values of 1 or 2 with length 550,000.

How can I save these values as either a 1 or a 2?

Upvotes: 1

Views: 2100

Answers (2)

Will
Will

Reputation: 24689

You can change the formatting of numeric values in the output. From the manual:

fmt : str or sequence of strs, optional

   A single format (%10.5f), a sequence of formats, or a multi-format string,
   e.g. ‘Iteration %d – %10.5f’, in which case delimiter is ignored.

So try:

np.savetxt('My_labels.csv', K, delimiter = ',', fmt='%d')

However, there are other problems with this code.

import numpy as np

def save_in_csv_format(My_Labels):
    np.savetxt('My_labels.csv', My_Labels, delimiter = ',', fmt='%d')

This should do exactly the same thing, and be much more efficient.

Upvotes: 1

jedwards
jedwards

Reputation: 30200

First thing to point out, assuming My_Labels is a list as you suggest, the indicated section of your code is superfluous:

def save_in_scv_format(My_Labels):
    import numpy as np
    K  = []                                 # <--
    for i in range(len(My_Labels)):         # <--
            K.append(My_Labels[i])          # <--

    np.savetxt('My_labels.csv', K, delimiter = ',')

You'd be just as well off writing:

def save_in_scv_format(My_Labels):
    import numpy as np

    np.savetxt('My_labels.csv', My_Labels, delimiter = ',')

But I don't think you need numpy to do what it seems you want to do. Something like:

def save_in_scv_format(My_Labels):
    with open('My_labels.csv', 'w') as f:
        f.write(','.join(My_Labels))

would likely work, and better.

Alternatively, you could do something like:

def save_in_scv_format(My_Labels):
    with open('My_labels.csv', 'w') as f:
        f.write(str(My_Labels))

which would preserve the enclosing square brackets, and add spaces between the integers.

There is also the csv and pickle modules, you might look into, for alternative means of outputting your list to a file.

n.b. If I misunderstood, and My_Labels is, for example, a numpy array, then something like:

my_array = My_Labels.tolist()

(docs) is a cleaner way of creating a python list.

Upvotes: 0

Related Questions