How to create a new csv from a csv that separated cell
I created a function for convert the csv. The main topic is: get a csv file like:
,features,corr_dropped,var_dropped,uv_dropped
0,AghEnt,False,False,False
and I want to conver it to an another csv file:
features | corr_dropped | var_dropped | uv_dropped | |
---|---|---|---|---|
0 | AghEnt | False | False | False |
I created a function for that but it is not working. The output is same as the input file.
function
def convert_file():
input_file = "../input.csv"
output_file = os.path.splitext(input_file)[0] + "_converted.csv"
df = pd.read_table(input_file, delimiter=',')
df.to_csv(output_file, index=False, header=True, sep=',')
It looks like there is a problem with the delimiter being used to read the input file. It's currently being set to ','
, but the input file seems to use ','
as the separator for values, not the delimiter between values and the next line.
Try changing the delimiter argument in pd.read_table()
to '\n'
:
def convert_file():
input_file = "../input.csv"
output_file = os.path.splitext(input_file)[0] + "_converted.csv"
df = pd.read_table(input_file, delimiter='\n')
df.to_csv(output_file, index=False, header=True, sep=',')
This should properly read the input file as a DataFrame
and write the output to a new file with the desired format.
you could use
df = pd.read_csv(input_file)
this works with your data. There is not much difference though. The only thing that changes is that the empty space before the first delimiter now has Unnamed: 0
in there.
Is that what you wanted? (Still not entirely sure what you are trying to achieve, as you are importing a csv and exporting the same data as a csv without really doing anything with it. the output example you showed is just a formated version of your initial data. but formating is not something csv can do.)