Home > Blockchain >  How to write csv file with numpy?
How to write csv file with numpy?

Time:04-26

I have two numpy arrays(A, B) and 2 scalar values(C,D) that I want to store in a csv file. I know how to write a single numpy array in it:

A = np.array(...)
np.savetxt('path/to/file/filename.csv', A, delimiter = ",")

I want the first two columns of my csv-file to contain the 2 arrays A and B and then have the 2 scalar values C and D as the first entry of columns 3 and 4.

CodePudding user response:

You need to transform the arrays first, maybe using zip_longest:

import csv
from itertools import zip_longest
import numpy as np

A = np.array(...)  # 1d arrays
B = np.array(...)
C = 1.0  # scalars
D = 2.0
with open('filename.csv', 'w', newline='') as f:
    w = csv.writer(f)
    for row in zip_longest(A, B, [C], [D], fillvalue=''):
        w.writerow(row)

If A and B are long, you will get lots of blank cells at the end of each row, which could be trimmed.

CodePudding user response:

I am assuming that all A and B are of the same length. I would use pandas to organise it the way I want then do pandas.DataFrame.to_csv() I would do:

import pandas as pd
import numpy as np

A = B = np.arange(5)  # 1d arrays
C = 1.0  # scalars
D = 2.0

df = pd.DataFrame({'A': A, 'B': B, 'C': np.NaN, 'D': np.NaN})
df.loc[0, 'C'] = C     # change 0 to 1 to fill the next row 
df.loc[0, 'D'] = D     # change 0 to 1 to fill the next row
df.to_csv('path/to/file/filename.csv')

CodePudding user response:

Since csv files are comma seperated values, terminology of column is more useful with excel files. If I understand correctly, you want your data shape like this

A1 B1 C D 
A2 B2  
A3 B3
.  .
.  .
.  .

It is very useful to change arrays to pandas dataframe and save whatever you like (excel or csv) . If we go back your question, solution could be like this:

A = np.array([1,2,3,4,5])
B = np.array([5,4,3,2,1])
C = [5]
D = [6]


_array = [A,B,C,D] #all values into list

data = pd.DataFrame(_array).T  # in order to get what you want, you have to transpose dataframe

data.to_csv('/Users/../data.csv')  # save as csv file

data.to_excel('/Users/../data.xlsx',index=False,header=False) # save as excel file to get column based
  • Related