Nankatsu
Nankatsu

Reputation: 55

Save different array into one csv file

I have an array of scores with values like

[[0.66372503]
 [0.64839758]
 [0.63307013]]

Then, I have an array of scores2 with values like

[[0.65367322]
 [0.63598164]
 [0.62295124]]

How do I combine them and save into csv like

         scores         scores2              
1     0.66372503     0.65367322
2     0.64839758     0.63598164
3     0.63307013     0.62295124

? Thank you

Upvotes: 0

Views: 381

Answers (3)

Scrappy Coco
Scrappy Coco

Reputation: 116

Try this:

scores = list(scores)
scores2 = list(scores2)
d = [scores, scores2]
export_data = zip_longest(*d, fillvalue = '')
with open('<your_file_name>.csv', 'w', encoding="ISO-8859-1", newline='') as myfile:
        wr = csv.writer(myfile)
        wr.writerow(("scores", "scores2"))
        wr.writerows(export_data)
    myfile.close()

Upvotes: 0

sash_wash
sash_wash

Reputation: 146

df= pd.DataFrame(data={'scores': [0.66372503, 0.64839758, 0.63307013],
                       'scores2':[0.65367322, 0.63598164, 0.62295124]})
df.to_csv('filename.csv', index=False)

if you have 2d array, you can use numpy flatten methode before passing the arrays into pandas df:

scores= [[0.66372503], [0.64839758], [0.63307013]]
scores2=[[0.65367322], [0.63598164], [0.62295124]]

df= pd.DataFrame(data={'scores': np.array(scores).flatten(),
                       'scores2':np.array(scores2).flatten()})

df.to_csv('filename.csv', index=False)

Upvotes: 2

OldManSeph
OldManSeph

Reputation: 2709

if you have basic python arrays you could do something like this:

n = len(scores)
for x in range(0,n):
    key = x + 1
    newline = key + "\t" + scores[x] + "\t" + scores2[x] + "\n"
    outf.write(newline)

Upvotes: 0

Related Questions