import numpy as np
# Write an example CSV file with headers on first line
with open('example.csv', 'w') as fp:
fp.write('''\
col1,col2,col3
1,100.1,string1
2,222.2,second string
''')
# Read it as a Numpy record array
ar = np.recfromcsv('example.csv', encoding='ascii')
print(repr(ar))
# rec.array([(1, 100.1, 'string1'), (2, 222.2, 'second string')],
# dtype=[('col1', '<i8'), ('col2', '<f8'), ('col3', '<U13')])
# Write as a CSV file with headers on first line
with open('out.csv', 'w') as fp:
fp.write(','.join(ar.dtype.names) + '\n')
np.savetxt(fp, ar, '%s', ',')
# format as a block of csv text to do whatever you want
csv_rows = ["{},{}".format(i, j) for i, j in array]
csv_text = "\n".join(csv_rows)
# write it to a file
with open('file.csv', 'w') as f:
f.write(csv_text)
# Libraries to import
import pandas as pd
import nump as np
#N x N numpy array (dimensions dont matter)
corr_mat #your numpy array
my_df = pd.DataFrame(corr_mat) #converting it to a pandas dataframe
例如#2:
#save as csv
my_df.to_csv('foo.csv', index=False) # "foo" is the name you want to give
# to csv file. Make sure to add ".csv"
# after whatever name like in the code