python-3.x - Pandas 在导入 csv 文件时删除空格/未知字符

标签 python-3.x pandas ubuntu

我可以下载文件:

seasons = [2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017]

epl_tables = {}
epl_seasons = {}
for year in seasons:
    start_year = str(year)[-2:]
    end_year = str(year+1)[-2:]
    season = start_year + end_year
    epl_seasons[season] = pd.read_csv("https://www.football-data.co.uk/mmz4281/{}{}/E0.csv".format(start_year, end_year)).dropna(how='all')
    epl_tables[season] = league(epl_seasons[season]) 

这工作正常。

但是,当我尝试通过将 2004 添加到季节来添加 2004-05 季节时,出现问题并且代码失败。
seasons = [2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017]

该问题是由 csv 文件第 337 到 345 行中裁判姓名前的空格引起的。

我可以通过手动删除空白然后从磁盘加载来解决这个问题,但显然它并不理想。

我已经尝试了各种方法来让它工作,如下所示,但似乎没有任何效果,
epl_seasons[season] = pd.read_csv("https://www.football-data.co.uk/mmz4281/{}{}/E0.csv".format(start_year, end_year), delimiter=',', encoding="utf-8", skipinitialspace=True).dropna(how='all')

一个潜在的复杂情况是,当我在 excel 中打开文件时,该空间显示为一个空格,但然后我在 libreCalc 中打开它(在 Ubuntu 中,这是我正在使用的),它显示为一个未知字符一个问号黑匣子倾斜 45 度。在下面的链接中查看 PeterMau 的答案,看看这个未知角色的样子。

https://ask.libreoffice.org/en/question/113125/characters-turned-into-question-marks/

有人可以告诉我谁可以自动删除这些空格/未知字符吗?

最佳答案

您可以使用 .str.strip(): 删除字符串中的空格。

epl_seasons[season]['COLUMN NAME'] = epl_seasons[season]['COLUMN NAME'].str.strip()

这不应该是一个手动过程。只需添加一行,以便在导入 CSV 文件时也可以清理有问题的列。

显然这仅适用于特定列。这是另一个线程上的答案,该线程解决了从每个 df 单元格中删除空格的问题:

Pythonic/efficient way to strip whitespace from every Pandas Data frame cell that has a stringlike object in it

关于python-3.x - Pandas 在导入 csv 文件时删除空格/未知字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59533504/

相关文章:

python - 使用 sort_value(inplace=True) 对数据框进行排序时出现错误

python - 具有增长率的 Pandas cumsum

python - 在 Pandas DataFrame 中拆分列表

c++ - 预编译 boost 库包 (Ubuntu)

Python 类变量初始化与 Python 3 不同

python - 如何直接从 python 脚本修改 Windows 10 路径变量

python - 错误 : gevent 1. 4.0 要求 greenlet>=0.4.14,但您将拥有不兼容的 greenlet 0.4.13

python - 高级 Python 3 循环迭代列表

python - 在 Ubuntu 上,如何安装更新版本的 python 并保留旧版本的 python?

java - Hadoop无法在Ubuntu 15.10上启动Datanode