0

I would like to write a csv file in Python 3 with the following format: "index, 0". E.g.:

0, 0

1, 0

2, 0

3, 0

...

I have written the following:

csv_file_object = csv.writer(open('file.csv', 'w', newline='')) 
Y=np.zeros(2508, dtype=int)
for index, y_aux in enumerate(Y):      
    csv_file_object.writerow([index, y_aux]) 

However, when I have opened the csv file, I can see:

0

1

2

3

...

How can I solve this? Thank you.

3
  • Does writing csv_file_object.writerow([index, str(y_aux)]) solve your problem? Commented Nov 3, 2017 at 19:19
  • 1
    What tool did you use to open the csv file? I can't reproduce your results. Commented Nov 3, 2017 at 19:23
  • Can you help us to understand your actual goal here? Are you trying to create a file with the indicated content? Or are you trying write an np.ndarray to a file, adding an index? To put it another way, is numpy an essential element of the solution? Commented Nov 3, 2017 at 19:37

2 Answers 2

1

This gets the desired output:

import csv

with open("my.csv", "w") as out:
    writer = csv.writer(out, delimiter=",")
    for i in xrange(1,10):
        writer.writerow([i,0])

But I don't know, what np.zeros(2508, dtype=int) is. Perhaps you elaborate a bit on your question.

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

2 Comments

np.zeroes is probably from import numpy as np.
@Robᵩ sounds good, but I haven't worked with numpy ;) so I can not confirm
0

It is not necessary to play with file i/o
There's an easier way

import numpy as np
import pandas as pd

mypath='your path here'

Y=np.zeros(2508, dtype=int)

convert to a pandas dataframe

U=pd.DataFrame(Y, columns=['zeros'])

U.head()     

    zeros
0   0
1   0
2   0
3   0
4   0

save directly to .csv

U.to_csv(mypath+'U.csv')

Comments

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.