Pandas 读取 Excel 文件去掉首尾的换行符

Pandas 库可以读取 Excel 文件、csv 文件等,但是 Windows 系统默认的换行符为 \r\n,这导致读取的数据末尾可能带有 \r,这会给后续的操作带来不便。不过,Pandas 有自带的方法可以方便地去掉这些特殊字符,比如 \r,\n,\t,空格。

我们手动构造一个含有上述换行符的 Series,使用 series.str.strip() 来清洗数据。

环境准备:

conda install pandas
conda install xlrd
conda install openpyxl

测试用例:

In [1]: import pandas as pd

In [2]: import numpy as np

In [3]: foo = pd.DataFrame({"name":["amy\n","bob\t","candy\r","dog\r\n","fish ",np.nan]})

In [4]: foo
Out[4]: 
      name
0    amy\n
1    bob\t
2  candy\r
3  dog\r\n
4    fish 
5      NaN

In [5]: foo["name"].str.strip()
Out[5]: 
0      amy
1      bob
2    candy
3      dog
4     fish
5      NaN
Name: name, dtype: object

结果显示是可以去除的。

下面读取 Excel 文件,用同样的方法尝试是否可行。

import pandas as pd

foo = pd.read_excel(
    "/home/junsircoding/Documents/test.xlsx",
    header=0,
    names=["name"]
)

foo["name"] = foo["name"].str.strip()
print(foo["name"])

结果:

0       amy\n
1       bob\t
2     candy\r
3     dog\r\n
4    fish    
Name: name, dtype: object

0      amy\n
1      bob\t
2    candy\r
3    dog\r\n
4       fish
Name: name, dtype: object

发现同样的方法无效。

这里需要将特殊字符转以,或者在字符串前加r前缀。

import pandas as pd

foo = pd.read_excel(
    "/home/junsircoding/Documents/test.xlsx",
    header=0,
    names=["name"]
)
print(foo["name"])

foo["name"] = foo["name"].str.strip(r"\n")
foo["name"] = foo["name"].str.strip(r"\r")
foo["name"] = foo["name"].str.strip(r"\t")
foo["name"] = foo["name"].str.strip(r"\r\n")
foo["name"] = foo["name"].str.strip()
print(foo["name"])

或:

import pandas as pd

foo = pd.read_excel(
    "/home/junsircoding/Documents/test.xlsx",
    header=0,
    names=["name"]
)
print(foo["name"])

foo["name"] = foo["name"].str.strip("\\n")
foo["name"] = foo["name"].str.strip("\\r")
foo["name"] = foo["name"].str.strip("\\t")
foo["name"] = foo["name"].str.strip("\\r\\n")
foo["name"] = foo["name"].str.strip()
print(foo["name"])

结果是符合预期的:

0       amy\n
1       bob\t
2     candy\r
3     dog\r\n
4    fish    
Name: name, dtype: object

0      amy
1      bob
2    candy
3      dog
4     fish
Name: name, dtype: object
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值