如何删除数据框中的回车 return

How to remove carriage return in a dataframe

我有一个数据框,其中包含名为 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() 时指定列名或行号。因为我不能确定只有 'location' 列会有 \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

使用 str.replace,您需要对序列进行转义,以便将其视为回车 return 而不是文字 \r:

In [15]:
df['29'] = df['29'].str.replace(r'\r','')
df

Out[15]:
             id             29
0      location  Uttar Pradesh
1  country_name          India
2  total_deaths             20

另一个解决方案是使用 str.strip:

df['29'] = df['29'].str.strip(r'\r')
print df
             id             29
0      location  Uttar Pradesh
1  country_name          India
2  total_deaths             20

如果要使用 replace,请添加 r 和一个 \:

print df.replace({r'\r': ''}, regex=True)
             id             29
0      location  Uttar Pradesh
1  country_name          India
2  total_deaths             20

replace 中,您可以定义要替换的列,例如:

print df
               id               29
0        location  Uttar Pradesh\r
1    country_name            India
2  total_deaths\r               20

print df.replace({'29': {r'\r': ''}}, regex=True)
               id             29
0        location  Uttar Pradesh
1    country_name          India
2  total_deaths\r             20

print df.replace({r'\r': ''}, regex=True)
             id             29
0      location  Uttar Pradesh
1  country_name          India
2  total_deaths             20

通过评论编辑:

import pandas as pd

df = pd.read_csv('data_source_test.csv')
print df
   id country_name           location  total_deaths
0   1        India          New Delhi           354
1   2        India         Tamil Nadu            48
2   3        India          Karnataka             0
3   4        India      Andra Pradesh            32
4   5        India              Assam           679
5   6        India             Kerala           128
6   7        India             Punjab             0
7   8        India      Mumbai, Thane             1
8   9        India  Uttar Pradesh\r\n            20
9  10        India             Orissa            69

print df.replace({r'\r\n': ''}, regex=True)
   id country_name       location  total_deaths
0   1        India      New Delhi           354
1   2        India     Tamil Nadu            48
2   3        India      Karnataka             0
3   4        India  Andra Pradesh            32
4   5        India          Assam           679
5   6        India         Kerala           128
6   7        India         Punjab             0
7   8        India  Mumbai, Thane             1
8   9        India  Uttar Pradesh            20
9  10        India         Orissa            69

如果只需要替换第location列:

df['location'] = df.location.str.replace(r'\r\n', '')
print df
   id country_name       location  total_deaths
0   1        India      New Delhi           354
1   2        India     Tamil Nadu            48
2   3        India      Karnataka             0
3   4        India  Andra Pradesh            32
4   5        India          Assam           679
5   6        India         Kerala           128
6   7        India         Punjab             0
7   8        India  Mumbai, Thane             1
8   9        India  Uttar Pradesh            20
9  10        India         Orissa            69

下面的代码删除了 \n 制表符空格、\n 换行符和 \r 回车符 return,非常适合将数据压缩到一行中。答案取自 https://gist.github.com/smram/d6ded3c9028272360eb65bcab564a18a

df.replace(to_replace=[r"\t|\n|\r", "\t|\n|\r"], value=["",""], regex=True, inplace=<INPLACE>)

只需让 df 等于 df.replace 代码行,然后打印 df。

df=df.replace({'\r': ''}, regex=True) 
print(df)

不知何故,接受的答案对我不起作用。最终,我按照 followed

的方式找到了解决方案
df["29"] = df["29"].replace(r'\r', '', regex=True)

区别是我用的是\r而不是\r