GVKun编程网logo

pandas read_csv dtype前导零(python前导0)

27

针对pandasread_csvdtype前导零和python前导0这两个问题,本篇文章进行了详细的解答,同时本文还将给你拓展API:详解pandas.read_csv、Flaskpandas.rea

针对pandas read_csv dtype前导零python前导0这两个问题,本篇文章进行了详细的解答,同时本文还将给你拓展API:详解 pandas.read_csv、Flask pandas.read_excel 不工作 - “没有这样的文件或目录” - 而 pandas.read-csv 适用于等效的 CSV 文件、numpy – 在pandas 0.10.1上使用pandas.read_csv指定dtype float32、pandas read_csv index_col =每行末尾都不能使用定界符等相关知识,希望可以帮助到你。

本文目录一览:

pandas read_csv dtype前导零(python前导0)

pandas read_csv dtype前导零(python前导0)

因此,我正在从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 pddf = pd.io.parsers.read_csv("Station Codes.csv",dtype={''USAF'': np.str, ''WBAN'': np.str})

要么

import pandas as pddf = 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)  File "parser.pyx", line 887, in pandas._parser.TextReader._convert_tokens (pandas\src\parser.c:8483)  File "parser.pyx", line 953, in pandas._parser.TextReader._convert_with_dtype (pandas\src\parser.c:9535)  File "parser.pyx", line 1283, in pandas._parser._to_fw_string (pandas\src\parser.c:14616)TypeError: data type not understood

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

答案1

小编典典

这是pandas dtype猜测的问题。

pandas看到数字,然后猜测您希望它是数字。

为了使熊猫不怀疑您的意图,应设置所需的dtype: object

pd.read_csv(''filename.csv'', dtype={''leading_zero_column_name'': object})

会成功的

更新,因为它可以帮助其他人:

要将所有列都设为str,可以执行此操作(根据评论):

pd.read_csv(''sample.csv'', dtype = str)

要将大多数或选择性的列设为str,可以执行以下操作:

# lst of column names which needs to be stringlst_str_cols = [''prefix'', ''serial'']# use dictionary comprehension to make dict of dtypesdict_dtypes = {x : ''str''  for x in lst_str_cols}# use dict on dtypespd.read_csv(''sample.csv'', dtype=dict_dtypes)

API:详解 pandas.read_csv

API:详解 pandas.read_csv

pandas.read_csv 作为常用的读取数据的常用API,使用频率非常高,但是API中可选的参数有哪些呢? 
pandas项目代码 
答案是:

.read_csv(filepath_or_buffer, sep=’, ‘, delimiter=None, header=’infer’, names=None, index_col=None, usecols=None, squeeze=False, prefix=None, mangle_dupe_cols=True, dtype=None, engine=None, converters=None, true_values=None, false_values=None, skipinitialspace=False, skiprows=None, nrows=None, na_values=None, keep_default_na=True, na_filter=True, verbose=False, skip_blank_lines=True, parse_dates=False, infer_datetime_format=False, keep_date_col=False, date_parser=None, dayfirst=False, iterator=False, chunksize=None, compression=’infer’, thousands=None, decimal=b’.’, lineterminator=None, quotechar=’”’, quoting=0, escapechar=None, comment=None, encoding=None, dialect=None, tupleize_cols=None, error_bad_lines=True, warn_bad_lines=True, skipfooter=0, skip_footer=0, doublequote=True, delim_whitespace=False, as_recarray=None, compact_ints=None, use_unsigned=None, low_memory=True, buffer_lines=None, memory_map=False, float_precision=None)

惊喜不惊喜,刺激不刺激?下面就详细解读下,个别参数的意义。(我个人认为有用的)

filepath_or_buffer : 路径 URL 可以是http, ftp, s3, 和 file.

sep: 指定分割符,默认是’,’C引擎不能自动检测分隔符,但Python解析引擎可以

delimiter: 同sep

delimiter_whitespace: True or False 默认False, 用空格作为分隔符等价于spe=’\s+’如果该参数被调用,则delimite不会起作用

header: 指定第几行作为列名(忽略注解行),如果没有指定列名,默认header=0; 如果指定了列名header=None

names 指定列名,如果文件中不包含header的行,应该显性表示header=None

index_col: 默认为None 用列名作为DataFrame的行标签,如果给出序列,则使用MultiIndex。如果读取某文件,该文件每行末尾都有带分隔符,考虑使用index_col=False使panadas不用第一列作为行的名称。

不知道你有没有看懂index_col最后一句话。反正我是没看懂,尝试了以后也没啥效果。后来尝试用下面方法来解决上述问题: 
其中test.txt 的内容为: 
1;2;3;4;5; 
6;7;8;2;5; 
注意这里how一定要用all,不然的话,一旦某一列出现na就会把整列数据删掉。

path2=''datas/test.txt''
df1 = pd.read_csv(path2, sep='';'',low_memory=False,header=None)
df1= df1.dropna(axis=1,how=''all'') df1.head() ## 获取前五行数据查看查看

usecols: 默认None 可以使用列序列也可以使用列名,如 [0, 1, 2] or [‘foo’, ‘bar’, ‘baz’]

as_recarray:默认False , 将读入的数据按照numpy array的方式存储,0.19.0版本后使用 
pd.read_csv(…).to_records()。 注意,这种方式读入的na数据不是显示na,而是给以个莫名奇妙的值

squeeze: 默认为False, True的情况下返回的类型为Series

prefix:默认为none, 当header =None 或者没有header的时候有效,例如’x’ 列名效果 X0, X1, …

mangle_dupe_cols :默认为True,重复的列将被指定为’X.0’…’X.N’,而不是’X’…’X’。如果传入False,当列中存在重复名称,则会导致数据被覆盖。

dtype: E.g. {‘a’: np.float64, ‘b’: np.int32} 指定数据类型

engine: {‘c’, ‘python’}, optional 选择读取的引擎目前来说C更快,但是Python的引擎有更多选择的操作

skipinitialspace: 忽略分隔符后的空格,默认false,

skiprows: list-like or integer or callable, default None 忽略某几行或者从开始算起的几行

skipfooter: 从底端算起的几行,不支持C引擎

nrows: int 读取的行数

na_values: 默认None NaN包含哪些情况,默认情况下, ‘#N/A’, ‘#N/A N/A’, ‘#NA’, ‘-1.#IND’, ‘-1.#QNAN’, ‘-NaN’, ‘-nan’, ‘1.#IND’, ‘1.#QNAN’, ‘N/A’, ‘NA’, ‘NULL’, ‘NaN’, ‘n/a’, ‘nan’, ‘null’. 都表现为NAN

keep_default_na: 如果na_values被定义,keep_default_na为False那么默认的NAN会被改写。 默认为True

na_filter: 默认为True, 针对没有NA的文件,使用na_filter=false能够提高读取效率

skip_blank_lines 默认为True,跳过blank lines 而且不是定义为NAN

thousands 千分位符号,默认‘,’

decimal 小数点符号,默认‘.’

encoding: 编码方式

memory_map如果为filepath_or_buffer提供了文件路径,则将文件对象直接映射到内存上,并直接从那里访问数据。使用此选项可以提高性能,因为不再有任何I / O开销。

low_memory 默认为True 在块内部处理文件,导致分析时内存使用量降低,但可能数据类型混乱。要确保没有混合类型设置为False,或者使用dtype参数指定类型。请注意,不管怎样,整个文件都读入单个DataFrame中,请使用chunksize或iterator参数以块形式返回数据。 (仅在C语法分析器中有效)

Flask pandas.read_excel 不工作 - “没有这样的文件或目录” - 而 pandas.read-csv 适用于等效的 CSV 文件

Flask pandas.read_excel 不工作 - “没有这样的文件或目录” - 而 pandas.read-csv 适用于等效的 CSV 文件

如何解决Flask pandas.read_excel 不工作 - “没有这样的文件或目录” - 而 pandas.read-csv 适用于等效的 CSV 文件?

以下将数据上传到数据库 (mongodb) 的方法适用于 CSV 文件,但不适用于 Excel 文件,尽管分别使用了 read_csv 和 read_excel。我也试图摆弄 read_excel 的参数,但没有成功。

我继续收到的错误是

FileNotFoundError: [Errno 2] No such file or directory: ''data2.xlsx''

CSV 和 Excel 文件数据相同,只是文件类型不同。


@app.route(''/<string:dbase>/fileupload'',methods=[''GET'',''POST''])
def file_upload(dbase):
    mydb = client[dbase]
    if request.method == ''POST'': 
        file = request.form.get(''fileupload'')
        split = os.path.splitext(file) # split[1] becomes file extension name e.g. ''.xlsx'' or ''.csv''
        if split[1] == ''.xlsx'' or split[1] == ''.xls'' or split[1] == ''.xlsm'' or split[1] == ''.xlsb'' or split[1] == ''.ods'':
            df=pd.read_excel(file)
        if split[1] == ''.csv'':
            df=pd.read_csv(file)
        accounts = df[''Account''].tolist()
        accs_to_add=[]
        for acc in accounts:
            accs_to_add.append(acc)
        accs_to_add = list(set(accs_to_add))
        for acc in accs_to_add:
            accs_col.insert_one({''Account'':acc})              
        return ''done''
    else:
        return render_template(''file_upload.html'',dbase=dbase)

感谢您的帮助

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

numpy – 在pandas 0.10.1上使用pandas.read_csv指定dtype float32

numpy – 在pandas 0.10.1上使用pandas.read_csv指定dtype float32

我试图读一个简单的空间分隔的文件用pandas read_csv方法。然而,熊猫似乎没有服从我的dtype参数。也许我错误地指定它?

我已经把我对read_csv的一些复杂的调用归结为这个简单的测试用例。我实际上在我的“真实”场景中使用转换器的参数,但我删除了为简单。

下面是我的ipython会话:

>>> cat test.out
a b
0.76398 0.81394
0.32136 0.91063
>>> import pandas
>>> import numpy
>>> x = pandas.read_csv('test.out',dtype={'a': numpy.float32},delim_whitespace=True)
>>> x
         a        b
0  0.76398  0.81394
1  0.32136  0.91063
>>> x.a.dtype
dtype('float64')

我也试过这个用numpy.int32或numpy.int64的dtype。这些选择导致异常:

AttributeError: 'nonetype' object has no attribute 'dtype'

我假设AttributeError是因为pandas不会自动尝试转换/截断浮点值为整数?

我在一个32位的机器上运行32位版本的Python。

>>> !uname -a
Linux ubuntu 3.0.0-13-generic #22-Ubuntu SMP Wed Nov 2 13:25:36 UTC 2011 i686 i686 i386 GNU/Linux
>>> import platform
>>> platform.architecture()
('32bit','ELF')
>>> pandas.__version__
'0.10.1'

解决方法

0.10.1并不真正支持float32

见http://pandas.pydata.org/pandas-docs/dev/whatsnew.html#dtype-specification

你可以在0.11这样做:

# dont' use dtype converters explicity for the columns you care about
# they will be converted to float64 if possible,or object if they cannot
df = pd.read_csv('test.csv'.....)

#### this is optional and related to the issue you posted ####
# force anything that is not a numeric to nan
# columns are the list of columns that you are interesetd in
df[columns] = df[columns].convert_objects(convert_numeric=True)


    # astype
    df[columns] = df[columns].astype('float32')

see http://pandas.pydata.org/pandas-docs/dev/basics.html#object-conversion

Its not as efficient as doing it directly in read_csv (but that requires

我已经确认用0.11-dev,这个DOES工作(对32位和64位,结果是一样的)

In [5]: x = pd.read_csv(StringIO.StringIO(data),dtype={'a': np.float32},delim_whitespace=True)

In [6]: x
Out[6]: 
         a        b
0  0.76398  0.81394
1  0.32136  0.91063

In [7]: x.dtypes
Out[7]: 
a    float32
b    float64
dtype: object

In [8]: pd.__version__
Out[8]: '0.11.0.dev-385ff82'

In [9]: quit()
vagrant@precise32:~/pandas$ uname -a
Linux precise32 3.2.0-23-generic-pae #36-Ubuntu SMP Tue Apr 10 22:19:09 UTC 2012 i686 i686 i386 GNU/Linux

 some low-level changes)

pandas read_csv index_col =每行末尾都不能使用定界符

pandas read_csv index_col =每行末尾都不能使用定界符

我正在阅读“
Python进行数据分析”一书,在“示例:2012年联邦选举委员会数据库”部分遇到了麻烦,无法将数据读取到DataFrame中。问题在于,即使将index_col参数设置为None,也总是将数据列之一设置为索引列。

这是数据的链接:http :
//www.fec.gov/disclosurep/PDownload.do。

这是加载代码(为节省检查时间,我将nrows设置为10):

import pandas as pdfec = pd.read_csv(''P00000001-ALL.csv'',nrows=10,index_col=None)

为了简短起见,我排除了数据列的输出,但这是我的输出(请不要提供索引值):

In [20]: fecOut[20]:<class ''pandas.core.frame.DataFrame''>Index: 10 entries, C00410118 to C00410118Data columns:...dtypes: float64(4), int64(3), object(11)

这是本书的输出(同样不包括数据列):

In [13]: fec = read_csv(''P00000001-ALL.csv'')In [14]: fecOut[14]:<class ''pandas.core.frame.DataFrame''>Int64Index: 1001731 entries, 0 to 1001730...dtypes: float64(1), int64(1), object(14)

我的输出中的Index值实际上是文件中数据的第一列,然后将所有其余数据向左移动一个。有谁知道如何防止将这列数据列为索引?我想让索引只是+1个递增的整数。

我对python和pandas相当陌生,因此给您带来的不便深表歉意。谢谢。

答案1

小编典典

快速回答

当每行的末尾有定界符时,请使用 index_col = False 而不是index_col = None来关闭索引列推断并丢弃最后一列。

更多详情

查看数据后,每行末尾都有一个逗号。以及这句话(自创建该帖子以来,文档已被编辑):

index_col:列号,列名或列号/名称的列表,用作所得DataFrame的索引(行标签)。默认情况下,它将对行进行编号而不使用任何列,除非数据列多于标题,在这种情况下,第一列将作为索引。

从文档显示,熊猫认为你有n个报头和n + 1列的数据,并且处理所述第一列作为索引。


编辑10/20/2014-更多信息

我找到了另一个有价值的条目,专门涉及尾随限制器以及如何简单地忽略它们:

如果文件中的数据列比列名的数量多,则第一列将用作DataFrame的行名:…

通常,您可以使用index_col选项来实现此行为。

在某些情况下,当在每个数据行的末尾使用分隔符准备文件时,会使解析器感到困惑。要显式禁用索引列推断并丢弃最后一列,请传递index_col =
False:…

今天关于pandas read_csv dtype前导零python前导0的介绍到此结束,谢谢您的阅读,有关API:详解 pandas.read_csv、Flask pandas.read_excel 不工作 - “没有这样的文件或目录” - 而 pandas.read-csv 适用于等效的 CSV 文件、numpy – 在pandas 0.10.1上使用pandas.read_csv指定dtype float32、pandas read_csv index_col =每行末尾都不能使用定界符等更多相关知识的信息可以在本站进行查询。

本文标签: