Home > Mobile >  saving csv file but it no seperate per columns
saving csv file but it no seperate per columns

Time:07-13

expcsv = {'PREDICTION OF' : ['CUTTING TEMPERATURE :','SURFACE ROUGHNESS :','CUTTING FORCE X :',
                                 'CUTTING FORCE Y :','CUTTING FORCE Z :'],
              'VALUE' : [out_arrct,out_arrra,out_arrfx,out_arrfy,out_arrfz],
              'METRICS' : ['°C','μm','N','N','N']
              }
    expcsvdf = pd.DataFrame(expcsv, columns=['PREDICTION OF', 'VALUE', 'METRICS'])
        
    data = [("csv file(*.csv)","*.csv")]
    file = asksaveasfilename(filetypes = data, defaultextension = data)
    with open(file,"w", encoding="utf-8") as f:
        f.write(str(expcsvdf))    

i had write columns to make it seperate on csv but it still merge in 1 column, if i am not writing str it can run well

CodePudding user response:

You should use pandas to_csv utility:

import pandas as pd

out_arrct, out_arrra, out_arrfx, out_arrfy, out_arrfz = 1, 2, 3, 4, 5

expcsv = {'PREDICTION OF' : ['CUTTING TEMPERATURE :','SURFACE ROUGHNESS :','CUTTING FORCE X :',
                                 'CUTTING FORCE Y :','CUTTING FORCE Z :'],
              'VALUE' : [out_arrct,out_arrra,out_arrfx,out_arrfy,out_arrfz],
              'METRICS' : ['°C','μm','N','N','N']
              }

expcsvdf = pd.DataFrame(expcsv, columns=['PREDICTION OF', 'VALUE', 'METRICS'])


# now let's save those to csv:
expcsvdf.to_csv('your_filename.csv', 
    sep=',',  # char used as separator between columns
    index=False, # do not save index column
    header=True  # do save headers
)

let's load the file to see how is it:

with open('your_filename.csv', 'r') as f:
    print(f.read())

the output is:

PREDICTION OF,VALUE,METRICS
CUTTING TEMPERATURE :,1,°C
SURFACE ROUGHNESS :,2,μm
CUTTING FORCE X :,3,N
CUTTING FORCE Y :,4,N
CUTTING FORCE Z :,5,N

And if you want to recover your dataframe, you just need this:

import pandas as pd

df = pd.read_csv('your_filename.csv', sep=',')
print(df)

where the output is:

           PREDICTION OF  VALUE METRICS
0  CUTTING TEMPERATURE :      1      °C
1    SURFACE ROUGHNESS :      2      μm
2      CUTTING FORCE X :      3       N
3      CUTTING FORCE Y :      4       N
4      CUTTING FORCE Z :      5       N
  • Related