Reputation: 735
I am a python beginner. I am given with a data file that contains something like the following: (these are tab separated)
(x values) (y values)
113 0
116 2
119 0
214 3
220 0
230 3
290 5
From the data file, I have to remove both x and y data that the y value is 0. This is done by the following.
import numpy as np
files = ['my_data.txt']
for file in files:
data = np.loadtxt(file,unpack=True)
data_filtered_both = data[:,data[1,:] != 0]
x_array=np.array(data_filtered_both[1])
y_array=np.array(data_filtered_both[0])
Now, I want to create a csv file that contains the new data file containing x_array and y_array (tab delimited). That looks something like this..
(x_array) (y_array)
116 2
214 3
230 3
290 5
So far, I have tried the following.
import csv
with open('text.csv', 'w') as f:
writer = csv.writer(f, delimiter='\t')
writer.writerows(zip(x_array,y_array)+'\n')
f.close()
My python shows an arrow at writer.writerows(zip(x_array,y_array)+'\n')
, indicating that that line may be written wrong. My kernel keeps dying without completing the task so I'm not sure exactly why it didn't work.
Is this the right way to create a csv file? Or is there any other suggestions?
Thanks!
Upvotes: 0
Views: 117
Reputation: 736
Without even using the csv module, below is how I approached this problem.
with open ("save_data.csv", "w") as file_object:
for y, x in zip (y_array, x_array):
file_object.write (("{}\t{}\n").format (y, x))
The code is pretty self-explanatory, but if you need an explanation on how it works I'd be more than happy to help :)
Also, remember than when using the 'with' statement, closing the file afterwards is not necessary as once all instructions within the indentation are finished executing, the file is closed automatically.
Upvotes: 1