简体   繁体   中英

How can I write entire data of a variable on a .csv file?

I would like to store entire values of a variable, Cp_cfd. Cp_cfd is from a database, and

print(Cp_cfd)

[[ 0.09487912  0.05570169  0.03011282 ...  0.19445465  0.18527783
   0.1675001 ]
 [ 0.094499    0.05298308  0.02696439 ...  0.19821845  0.18978267
   0.17296235]
 [ 0.08363242  0.0591914   0.02952287 ...  0.19714396  0.18762188
   0.1678648 ]
 ...
 [-0.02592602 -0.0313541  -0.04409973 ...  0.24386039  0.20862401
   0.1491545 ]
 [-0.0824953  -0.04109486 -0.05317128 ...  0.23705224  0.20034774
   0.13957643]
 [-0.09290421 -0.05173297 -0.06361054 ...  0.23318158  0.19520814
   0.13199864]]

Cp_cfd.shape is (11466, 74)

I made a code to store the values as below

def convert_rae(outf, obj):
    o = open(outf, "w")

    for i in range(len(obj)):
        o.write(str(obj[:,i]) + "\n")

    o.close()

convert_rae("rae_test.csv",Cp_cfd)

but it gives me an error

index 74 is out of bounds for axis 1 with size 74

How can I efficiently (may look good) store the values without error?

when you loop on len(obj) = 11466 and access obj[:, i] you will try accessing index out of its 74 columns. you probably mean obj[i, :] ?

The best way to accomplish this would be to use the csv library

import csv

def convert_rae(outf, obj):
    with open(outf, "w", newline='') as csvfile:
        csvwriter = csv.writer(csvfile)
        csvwriter.writerows(obj)

convert_rae("rae_test.csv",Cp_cfd)

This may or may not work depending on what kind of object you're working with.

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