How do I save two arrays as a text file with tab as a column delimiter?

Viewed 258

I have two numpy arrays. Array1 contains the wavelength value and array2 contains the flux value.

 array1=[5625.04152255 5625.11815852 5625.19478889 ... 6020.79150447 6020.86486562
         6020.93822138]
 array2=[0.93763397 0.89685317 0.9532884  ... 1.0172066  0.9948189  1.00680107]

The first wavelength in array1 has the first flux of array2 as its pair and I want to save them as a text file with the first line being the header names 'wavelength' and 'flux'

wavelength       flux          
5625.04152255 0.93763397
5625.11815852 0.89685317 
5625.19478889 0.9532884 
3 Answers

start by making a single np.array

import numpy as np
full_array = np.stack([array1, array2], axis=1)

then save txt with header

np.savetxt("filename.txt", full_array, delimiter="\t", header="wavelength\tflux", comments='')

This will do your job:

    array1=[5625.04152255 5625.11815852 5625.19478889 6020.79150447 
                 6020.86486562 6020.93822138]
    
    array2=[0.93763397 0.89685317 0.9532884 1.0172066  0.9948189 1.00680107]
    
    with open('./data.txt', 'w') as file:
        file.write('wavelength\tflux\n')
    
        for i in range(len(array1)):
            file.write(f'{array1[i]}\t{array2[i]}\n')
        
    file.close()
    array1=[5625.04152255 5625.11815852 5625.19478889 ... 6020.79150447 6020.86486562
     6020.93822138]
    array2=[0.93763397 0.89685317 0.9532884  ... 1.0172066  0.9948189  1.00680107]
    with open("flux.txt", "w") as fd:
        fd.write("Wavelength    flux")
        for wl, f in zip(array1, array2):
            fd.write("{}               {}".format(wl,f))
Related