Dump a NumPy array into a csv file
numpy.savetxt
saves an array to a text file.
import numpy
a = numpy.asarray([ [1,2,3], [4,5,6], [7,8,9] ])
numpy.savetxt("foo.csv", a, delimiter=",")
How can I export my NUMPY array into a CSV or EXCEL file
You can use Pandas
to save your NumPy array as CSV (See here)
Suppose numArr
is your numpy array. And you can do like this:
import pandas as pd
df = pd.DataFrame(numArr)
df.to_csv('file.csv',index=False)
How to store array of numpy array in csv file?
You could save the numpy array using numpy.save
as shown in the docs here. You could save the image name and image path as a .json
file (and just make the name of the .npy
file the same as the name as the .json
file to allow for easier searching).
How to save numpy ndarray as .csv file?
Your array include strings, but np default formatting is for floats.
Try manually setting the format:
np.savetxt(r'g:\test.csv',ab,delimiter=',', fmt=('%s, %f'))
How to write an object typed array into csv file with NumPy?
I think you must use iterations or other libraries e.g. Pandas to do this, because each of the columns will have a different size (in this example we will handle unequal sizes of A and B). So the saved array must be specified as object type if you want to do this by np.savetxt
. If you use object typed array to be saved by np.savetxt
, it will just fill the first row of the csv file:
A = np.array([2, 4.1, 5], dtype=np.float64)
B = np.array([2, 7, 9, 1], dtype=np.float64)
C = 1
D = 7
Output = np.zeros((1, 4), dtype=object)
Output[0, :] = A, B, C, D
np.savetxt('Output.csv', Output, delimiter=",", fmt='%s')
which will be as:
I don't think if it can be good handled just by NumPy, and will be better to try by other libraries such as Pandas or … or use iterations to open the csv file and import in it. But if you want to use NumPy for doing so (just for figuring out how to do this work by NumPy), it can be achieved by padding to equalize the arrays' sizes in indirect way. For this aim, we must find maximum length of the A
and B
to pad the arrays to that length. I filled the padded indices by np.nan
in this example and then removed it for the output:
max_len = max(A.shape[0], B.shape[0])
A_pad = np.pad(A, (0, max_len - A.shape[0]), constant_values=(np.nan,))
B_pad = np.pad(B, (0, max_len - B.shape[0]), constant_values=(np.nan,))
C_pad = np.pad(np.array([C], dtype=np.float64), (0, max_len - 1), constant_values=(np.nan,))
D_pad = np.pad(np.array([D], dtype=np.float64), (0, max_len - 1), constant_values=(np.nan,))
Output = np.array([A_pad, B_pad, C_pad, D_pad]).T
Output = Output.astype(str)
Output[Output == 'nan'] = ''
np.savetxt('Output.csv', Output, delimiter=",", fmt="%s")
Saving a list containing a numpy array in CSV format in Python
In your code, you are using the file to write your lines rather than the csv writer. Use the csv writer with the writerow
function to write a single row to the CSV file:
with open('Data_sigma.csv', 'w') as f:
writer = csv.writer(f)
writer.writerow(sigma1[0])
Note, as sigma1 is a list containing the NumPy array, we have written out sigma1[0]
. If you have multiple NumPy arrays in sigma1 then you can write all of these out to your file using writerows
as follows:
with open('Data_sigma.csv', 'w') as f:
writer = csv.writer(f)
writer.writerows(sigma1)
Writing a list of NumPy arrays to csv
You can un-nest data
with itertools.chain.from_iterable
and use wr.writerow
.
>>> from itertools import chain
>>>
>>> with open("data.csv", mode='w') as csvfile:
...: wr = csv.writer(csvfile, quoting=csv.QUOTE_ALL, dialect="excel")
...: wr.writerow(chain.from_iterable(data))
Output:
$ cat data.csv
"178.0","76.0","184.0","92.0","164.0","90.0","154.0","116.0","160.0","126.0","204.0","94.0","208.0","124.0","190.0","132.0","164.0","152.0"
Export numpy array in a for loop into one CSV in Python
with open("output.csv", "a") as f: # use 'a' instead of 'ab'
np.savetxt(f, img_binary, fmt="%d", delimiter=",")
f.write("\n")
You should open your file in append mode. Or by default savetxt() rewrites the file everytime.
Related Topics
How to Get an Absolute File Path in Python
How to Catch and Print the Full Exception Traceback Without Halting/Exiting the Program
Remove Pandas Rows with Duplicate Indices
Why Should I Make a Copy of a Data Frame in Pandas
Generate Random Numbers with a Given (Numerical) Distribution
Convert Python Datetime to Epoch with Strftime
Regular Expression to Return Text Between Parenthesis
Regular Expression to Match a Dot
Threading.Timer - Repeat Function Every 'N' Seconds
Is There a Simple Way to Delete a List Element by Value
Tensorflow Not Found Using Pip
Iterate an Iterator by Chunks (Of N) in Python
How Are Tuples Unpacked in for Loops
Scheduling a Regular Event: Cron/Cron Alternatives (Including Celery)
Why Does Python Code Run Faster in a Function