Ad

Remove Line Break After CSV File Aggregation

- 1 answer

I am aggregating data in a CVS file, the code:

import pandas
df = pandas.read_csv("./input.csv", delimiter=";", low_memory=False)
df.head()
count_severity = df.groupby("PHONE")["IMEI"].unique()
has_multiple_elements = count_severity.apply(lambda x: len(x)>1)
result = count_severity[has_multiple_elements]
result.to_csv("./output.csv", sep=";")

and in some lines of the received file, I get the following:

enter image description here

It turns out that I get the second column, which is after the sign ;, divided into two rows.

Could you tell me please, how to get rid of this line break? I tried adding a parameter line_terminator=None in result.to_csv - it didn't help.

Any method is accepted, even if you have to overwrite this file and save a new one. I also tried this:

import pandas as pd    
output_file = open("./output.csv", "r")   
output_file = ''.join([i for i in output_file]).replace("\n", "")
output_file_new = open("./output_new.csv", "w")
output_file_new.writelines(output_file)
output_file_new.close()

But then I get solid lines, which is not good at all.

To summarize, I should get the format of this file:

enter image description here

Thank You!

Ad

Answer

If your wrong lines always start with a comma, you could just replace the sequence "\n," by ",".

with open("./output.csv", "r") as file:
    content = file.read()
new_content = content.replace("\n,", ",")
with open("./new_output.csv", "w") as file:
    file.write(new_content)
Ad
source: stackoverflow.com
Ad