I am having a dataframe that contains columns named id, country_name, location and total_deaths. While doing data cleaning process, I came across a value in a row that has '\r'
attached. Once I complete cleaning process, I store the resulting dataframe in destination.csv file. Since the above particular row has \r
attached, it always creates a new row.
id 29
location Uttar Pradesh\r
country_name India
total_deaths 20
I want to remove \r
. I tried df.replace({'\r': ''}, regex=True)
. It isn't working for me.
Is there any other solution. Can somebody help?
Edit:
In the above process, I am iterating over df to see if \r
is present. If present, then need to replace. Here row.replace()
or row.str.strip()
doesn't seem to be working or I could be doing it in a wrong way.
I don't want specify the column name or row number while using replace()
. Because I can't be certain that only 'location' column will be having \r
. Please find the code below.
count = 0
for row_index, row in df.iterrows():
if re.search(r"\\r", str(row)):
print type(row) #Return type is pandas.Series
row.replace({r'\\r': ''} , regex=True)
print row
count += 1
use
str.replace
, you need to escape the sequence so it treats it as a carriage return rather than the literal\r
:The below code removes \n tab spaces, \n new line and \r carriage return and is great for condensing datum into one row. The answer was taken from https://gist.github.com/smram/d6ded3c9028272360eb65bcab564a18a
Another solution is use
str.strip
:If you want use
replace
, addr
and one\
:In
replace
you can define column for replacing like:EDIT by comment:
If need replace only in column
location
:Just make df equal to the df.replace code line and then print df.