熊猫read_csv dtype前导零

因此,我正在从NOAA读取站代码csv文件,如下所示:


"USAF","WBAN","STATION NAME","CTRY","FIPS","STATE","CALL","LAT","LON","ELEV(.1M)","BEGIN","END"

"006852","99999","SENT","SW","SZ","","","+46817","+010350","+14200","",""

"007005","99999","CWOS 07005","","","","","-99999","-999999","-99999","20120127","20120127"

前两列包含气象站代码,有时它们的前导零。当熊猫在未指定dtype的情况下导入它们时,它们将变成整数。没什么大不了的,因为我可以遍历数据框索引并用类似的东西替换它们,"%06d" % i因为它们始终是六位数,但是您知道...这是懒惰的方式。


使用以下代码获取csv:


file = urllib.urlopen(r"ftp://ftp.ncdc.noaa.gov/pub/data/inventories/ISH-HISTORY.CSV")

output = open('Station Codes.csv','wb')

output.write(file.read())

output.close()

一切都很好,但是当我去尝试使用以下方法阅读它时:


import pandas as pd

df = pd.io.parsers.read_csv("Station Codes.csv",dtype={'USAF': np.str, 'WBAN': np.str})

或者


import pandas as pd

df = pd.io.parsers.read_csv("Station Codes.csv",dtype={'USAF': str, 'WBAN': str})

我收到一个讨厌的错误消息:


File "C:\Python27\lib\site-packages\pandas-0.11.0-py2.7-win32.egg\pandas\io\parsers.py", line 401, in parser

_f

    return _read(filepath_or_buffer, kwds)

  File "C:\Python27\lib\site-packages\pandas-0.11.0-py2.7-win32.egg\pandas\io\parsers.py", line 216, in _read

    return parser.read()

  File "C:\Python27\lib\site-packages\pandas-0.11.0-py2.7-win32.egg\pandas\io\parsers.py", line 633, in read

    ret = self._engine.read(nrows)

  File "C:\Python27\lib\site-packages\pandas-0.11.0-py2.7-win32.egg\pandas\io\parsers.py", line 957, in read

    data = self._reader.read(nrows)

  File "parser.pyx", line 654, in pandas._parser.TextReader.read (pandas\src\parser.c:5931)

  File "parser.pyx", line 676, in pandas._parser.TextReader._read_low_memory (pandas\src\parser.c:6148)

  File "parser.pyx", line 752, in pandas._parser.TextReader._read_rows (pandas\src\parser.c:6962)

  File "parser.pyx", line 837, in pandas._parser.TextReader._convert_column_data (pandas\src\parser.c:7898)

这是一个相当大的csv(3万1千行),所以也许与此有关吗?


犯罪嫌疑人X
浏览 179回答 3
3回答

温温酱

这个问题让我在解析带有序列号的文件时遇到了种种麻烦。出于未知原因,00794和000794是两个不同的序列号。我最终想出了converters = {'serial_number': str}

达令说

如果您不希望字符串成为对象,则似乎必须指定字符串的长度。例如:dtype={'USAF': '|S6'}我找不到相关的参考,但我似乎想起了Wes在讨论这个问题(也许是在谈话中)。他建议numpy不允许使用“适当的”可变长度的字符串(请参阅此问题/答案),并且使用最大长度填充数组通常会导致空间效率低下(即使字符串较短,它也会使用与最长的字符串一样多的空间)。正如@Wes指出的,这也是以下情况:dtype={'USAF': object}效果也一样。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python