【发布时间】:2016-09-06 18:05:46
【问题描述】:
我有一个数据框,其中包含名为 id、country_name、location 和 total_deaths 的列。在进行数据清理过程中,我在一行中发现了一个附加了'\r' 的值。完成清理过程后,我将生成的数据帧存储在destination.csv 文件中。由于上述特定行附加了\r,因此它总是会创建一个新行。
id 29
location Uttar Pradesh\r
country_name India
total_deaths 20
我想删除\r。我试过df.replace({'\r': ''}, regex=True)。它不适合我。
还有其他解决办法吗?有人可以帮忙吗?
编辑:
在上述过程中,我正在遍历 df 以查看是否存在 \r。如果存在,则需要更换。这里row.replace() 或row.str.strip() 似乎不起作用,或者我可能以错误的方式进行操作。
我不想在使用replace() 时指定列名或行号。因为我不能确定只有“位置”列会有\r。请在下面找到代码。
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
【问题讨论】:
-
而
df.replace({r'\\r': ''}, regex=True)也不起作用?为什么使用iterrows()?我认为这不是必需的,因为迭代非常慢。 -
我没有其他方法可以迭代 df。
df.replace({r'\\r': ''}, regex=True)不工作
标签: python pandas replace carriage-return data-cleaning