简体   繁体   中英

How can I write a zero-array in a csv file in python?

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

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.

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.

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')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM