0

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!

1

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Hi! Thanks for helping. This works. The only question I have is about (str(y), str(x)). Do we need to use "str"?
No, you do not. Sorry, I just added that due to force of habit. You can safely remove the str to leave you with .format (y, x) and everything should still work fine :) I have edited my answer, thanks for pointing this out.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.