Py之pandas:pandas的read_excel()函数中各参数说明及函数使用方法讲解
Py之pandas:pandas的read_excel()函数中各参数说明及函数使用方法讲解pandas的read_excel()函数中各参数说明及函数使用方法讲解read_excel()函数实现功能将一个Excel文件读入一个pandas数据文件夹。支持从本地文件系统或URL读取的xls、xlsx、xlsm、xlsb、odf、ods和odt文件扩展名。支持读取单个工作表或工作表列表的选项。read_excel()函数使用方法1、可以使用文件名作为字符串或打开文件对象来读取文件:pd.read_excel('tmp.xlsx', index_col=0) Name Value0 string1 11 string2 22 #Comment 3pd.read_excel(open('tmp.xlsx', 'rb'), sheet_name='Sheet3') Unnamed: 0 Name Value0 0 string1 11 1 string2 22 2 #Comment 3 2、索引和标头可以通过index_col和标头参数指定pd.read_excel('tmp.xlsx', index_col=None, header=None) 0 1 20 NaN Name Value1 0.0 string1 12 1.0 string2 23 2.0 #Comment 3 3、列类型是推断式的,但可以显式指定pd.read_excel('tmp.xlsx', index_col=0, dtype={'Name': str, 'Value': float}) Name Value0 string1 1.01 string2 2.02 #Comment 3.0 4、True、False和NA值以及数千个分隔符都有默认值,但也可以显式指定。提供您想要的值作为字符串或字符串列表!pd.read_excel('tmp.xlsx', index_col=0, na_values=['string1', 'string2']) Name Value0 NaN 11 NaN 22 #Comment 3 read_excel()函数中各参数具体说明官方API:pandas.read_exceldef read_excel Found at: pandas.io.excel._base@deprecate_nonkeyword_arguments(allowed_args=2, version="2.0")@Appender(_read_excel_doc)def read_excel( io, sheet_name=0, header=0, names=None, index_col=None, usecols=None, squeeze=False, dtype=None, engine=None, converters=None, true_values=None, false_values=None, skiprows=None, nrows=None, na_values=None, keep_default_na=True, na_filter=True, verbose=False, parse_dates=False, date_parser=None, thousands=None, comment=None, skipfooter=0, convert_float=True, mangle_dupe_cols=True):iostr, bytes, ExcelFile, xlrd.Book, path object, or file-like objectAny valid string path is acceptable. The string could be a URL. Valid URL schemes include http, ftp, s3, and file. For file URLs, a host is expected. A local file could be: file://localhost/path/to/table.xlsx. If you want to pass in a path object, pandas accepts any os.PathLike. By file-like object, we refer to objects with a read() method, such as a file handler (e.g. via builtin open function) or StringIO.str, bytes, ExcelFile, xlrd.Book, path object, , or file-like object任何有效的字符串路径。字符串可以是URL。有效的URL方案包括http、ftp、s3和file。对于文件url,需要一个主机。本地文件可以是:file://localhost/path/to/table.xlsx。如果您想传入一个path对象,pandas会接受任何类似os. path的东西。通过类文件对象,我们使用read()方法引用对象,比如文件处理程序(例如通过内置的open函数)或StringIO。sheet_namestr, int, list, or None, default 0Strings are used for sheet names. Integers are used in zero-indexed sheet positions. Lists of strings/integers are used to request multiple sheets. Specify None to get all sheets.Available cases:Defaults to 0: 1st sheet as a DataFrame1: 2nd sheet as a DataFrame"Sheet1": Load sheet with name “Sheet1”[0, 1, "Sheet5"]: Load first, second and sheet named “Sheet5” as a dict of DataFrameNone: All sheets.表格名称使用str、int、list或None等默认0字符串。整数用于零索引的工作表位置。字符串/整数列表用于请求多个表。指定None以获取所有表。可用情况:默认为0:第1张表作为DataFrame1:第2张表作为DataFrame“Sheet1”:加载名称为“Sheet1”的表[0,1,“Sheet5”]:首先加载,第二张和名为“Sheet5”的表作为DataFrameNone的dict:所有表。sheet_name=sheetname_ID, 指定要读入的sheet名headerint, list of int, default 0Row (0-indexed) to use for the column labels of the parsed DataFrame. If a list of integers is passed those row positions will be combined into a MultiIndex. Use None if there is no header.行(0索引),用于已解析的数据格式的列标签。如果传递了一个整数列表,那么这些行位置将合并到一个多索引中。如果没有标题,则使用None。namesarray-like, default NoneList of column names to use. If file contains no header row, then you should explicitly pass header=None.要使用的列名的列表。如果文件不包含头行,那么应该显式传递header=None。使用names参数时,类似重命名。切记,要与原数据全部匹配:即不能多也不能少,多或者少都会抛出ValueError错误。index_colint, list of int, default NoneColumn (0-indexed) to use as the row labels of the DataFrame. Pass None if there is no such column. If a list is passed, those columns will be combined into a MultiIndex. If a subset of data is selected with usecols, index_col is based on the subset.Column(0索引)用作数据格式的行标签。如果没有这样的列,则传递None。如果传递了一个列表,那么这些列将被合并到一个多索引中。如果使用usecols选择了数据子集,则index_col基于该子集。index_col=0, #不读取第一索引列usecolsint, str, list-like, or callable default NoneIf None, then parse all columns.If str, then indicates comma separated list of Excel column letters and column ranges (e.g. “A:E” or “A,C,E:F”). Ranges are inclusive of both sides.If list of int, then indicates list of column numbers to be parsed.If list of string, then indicates list of column names to be parsed.New in version 0.24.0.If callable, then evaluate each column name against it and parse the column if the callable returns True.Returns a subset of the columns according to behavior above.New in version 0.24.0.如果没有,那么解析所有列。如果str,则表示用逗号分隔的Excel列字母和列范围列表(如“A:E”或“A,C,E:F”)。范围包括两边。如果list of int,则指示要解析的列号列表。如果字符串列表,则指示要解析的列名列表。新版本为0.24.0。usecols=[1,2,7,8,14]usecols参数,指定要读入列的索引IDsqueezebool, default FalseIf the parsed data only contains one column then return a Series.如果解析的数据只包含一列,则返回一个序列。dtypeType name or dict of column -> type, default NoneData type for data or columns. E.g. {'a’: np.float64, 'b’: np.int32} Use object to preserve data as stored in Excel and not interpret dtype. If converters are specified, they will be applied INSTEAD of dtype conversion.数据或列的数据类型。例如{a: np。使用object保存存储在Excel中的数据,而不是解释dtype。如果指定了转换器,则将应用它们而不是dtype转换。enginestr, default NoneIf io is not a buffer or path, this must be set to identify io. Supported engines: “xlrd”, “openpyxl”, “odf”, “pyxlsb”, default “xlrd”. Engine compatibility : - “xlrd” supports most old/new Excel file formats. - “openpyxl” supports newer Excel file formats. - “odf” supports OpenDocument file formats (.odf, .ods, .odt). - “pyxlsb” supports Binary Excel files.如果io不是缓冲区或路径,则必须将其设置为识别io。支持的引擎:“xlrd”、“openpyxl”、“odf”、“pyxlsb”,默认为“xlrd”。引擎兼容性:-“xlrd”支持大多数新旧Excel文件格式。- " openpyxl "支持较新的Excel文件格式。-“odf”支持OpenDocument文件格式(。odf。ods, .odt)。- " pyxlsb "支持二进制Excel文件。convertersdict, default NoneDict of functions for converting values in certain columns. Keys can either be integers or column labels, values are functions that take one input argument, the Excel cell content, and return the transformed content.用于转换某些列中的值的函数的字典。键可以是整数也可以是列标签,值是接受一个输入参数Excel单元格内容并返回转换后内容的函数。true_valueslist, default NoneValues to consider as True.true_valuesfalse_valueslist, default NoneValues to consider as False.false_valuesskiprowslist-likeRows to skip at the beginning (0-indexed).开头要跳过的行(0索引)。nrowsint, default NoneNumber of rows to parse.New in version 0.23.0.要解析的行数。新版本0.23.0。na_valuesscalar, str, list-like, or dict, default NoneAdditional strings to recognize as NA/NaN. If dict passed, specific per-column NA values. By default the following values are interpreted as NaN: '’, '#N/A’, '#N/A N/A’, '#NA’, '-1.#IND’, '-1.#QNAN’, '-NaN’, '-nan’, '1.#IND’, '1.#QNAN’, '<NA>’, 'N/A’, 'NA’, 'NULL’, 'NaN’, 'n/a’, 'nan’, 'null’.附加的弦可以像NA/NaN那样识别。如果命中注定,具体的评估。例如:“'N/A’、'N/A’、'N/A’、'NA’、'-1’。”# IND”、“录音。QNAN ', ' -NaN ', ' -NaN ', ' 1。# IND”、“1。# QNAN NA系”、“< >”、“N / A”、“NA”、“空”、“南”、“N / A'南’,'空’。keep_default_nabool, default TrueWhether or not to include the default NaN values when parsing the data. Depending on whether na_values is passed in, the behavior is as follows:If keep_default_na is True, and na_values are specified, na_values is appended to the default NaN values used for parsing.If keep_default_na is True, and na_values are not specified, only the default NaN values are used for parsing.If keep_default_na is False, and na_values are specified, only the NaN values specified na_values are used for parsing.If keep_default_na is False, and na_values are not specified, no strings will be parsed as NaN.Note that if na_filter is passed in as False, the keep_default_na and na_values parameters will be ignored.解析数据时是否包含默认的NaN值。根据是否传入na_values,行为如下:如果keep_default_na为真,并且指定了na_values,那么na_values将附加到用于解析的缺省NaN值中。如果keep_default_na为真,并且没有指定na_values,则只使用默认的NaN值进行解析。如果keep_default_na为False,并且指定了na_values,则仅使用指定na_values的NaN值进行解析。如果keep_default_na为False,并且没有指定na_values,则不会将任何字符串解析为NaN。注意,如果将na_filter作为False传入,则keep_default_na和na_values参数将被忽略。na_filterbool, default TrueDetect missing value markers (empty strings and the value of na_values). In data without any NAs, passing na_filter=False can improve the performance of reading a large file.检测缺失的值标记(空字符串和na_values的值)。在没有NAs的数据中,传递na_filter=False可以提高读取大文件的性能。verbosebool, default FalseIndicate number of NA values placed in non-numeric columns.指示放置在非数字列中的NA值的数目。parse_datesbool, list-like, or dict, default FalseThe behavior is as follows:bool. If True -> try parsing the index.list of int or names. e.g. If [1, 2, 3] -> try parsing columns 1, 2, 3 each as a separate date column.list of lists. e.g. If [[1, 3]] -> combine columns 1 and 3 and parse as a single date column.dict, e.g. {'foo’ : [1, 3]} -> parse columns 1, 3 as date and call result 'foo’If a column or index contains an unparseable date, the entire column or index will be returned unaltered as an object data type. If you don`t want to parse some cells as date just change their type in Excel to “Text”. For non-standard datetime parsing, use pd.to_datetime after pd.read_excel.Note: A fast-path exists for iso8601-formatted dates.其行为如下:bool类型:如果为真——>尝试解析索引。int或名称的列表。例如,If[1,2,3] ->尝试将1,2,3列分别解析为一个单独的日期列。list类型:例如,If[[1,3]] ->组合列1和3并解析为单个日期列。dict类型:例如{' foo ':[1,3]} ->解析列1,3作为日期并调用结果' foo '如果列或索引包含不可解析的日期,则整个列或索引将作为对象数据类型不变地返回。如果你不想把一些单元格解析为date,那就把它们在Excel中的类型改为Text。对于非标准的日期时间解析,在pd.read_excel后面使用pd.to_datetime。注意:有一个用于iso8601格式的日期的快速路径。date_parserfunction, optionalFunction to use for converting a sequence of string columns to an array of datetime instances. The default uses dateutil.parser.parser to do the conversion. Pandas will try to call date_parser in three different ways, advancing to the next if an exception occurs: 1) Pass one or more arrays (as defined by parse_dates) as arguments; 2) concatenate (row-wise) the string values from the columns defined by parse_dates into a single array and pass that; and 3) call date_parser once for each row using one or more strings (corresponding to the columns defined by parse_dates) as arguments.该函数,用于将字符串列序列转换为日期时间实例数组。默认使用dateutil.parser。解析器执行转换。熊猫将尝试以三种不同的方式调用date_parser,如果出现异常,则继续调用:1)传递一个或多个数组(由parse_date定义)作为参数;2)将parse_date定义的列中的字符串值连接到一个数组中并传递它;使用一个或多个字符串(对应于parse_date定义的列)作为参数,对每一行调用date_parser一次。thousandsstr, default NoneThousands separator for parsing string columns to numeric. Note that this parameter is only necessary for columns stored as TEXT in Excel, any numeric columns will automatically be parsed, regardless of display format.数以千计的分隔符用于将字符串列解析为数字。请注意,此参数仅对存储为文本的列在Excel中是必要的,任何数值列都将自动解析,无论显示格式如何。commentstr, default NoneComments out remainder of line. Pass a character or characters to this argument to indicate comments in the input file. Any data between the comment string and the end of the current line is ignored.注释掉行中的余数。向此参数传递一个或多个字符,以指示输入文件中的注释。注释字符串和当前行结束之间的任何数据都将被忽略。skipfooterint, default 0Rows at the end to skip (0-indexed).末尾要跳过的行(0索引)。convert_floatbool, default TrueConvert integral floats to int (i.e., 1.0 –> 1). If False, all numeric data will be read in as floats: Excel stores all numbers as floats internally.将整型浮点数转换为整型浮点数(例如,1.0 - > - 1),如果为False,则所有数值数据将以浮点数的形式读入:Excel在内部将所有数字存储为浮点数。mangle_dupe_colsbool, default TrueDuplicate columns will be specified as 'X’, 'X.1’, …’X.N’, rather than 'X’…’X’. Passing in False will cause data to be overwritten if there are duplicate names in the columns.重复列将被指定为' X ', ' X。1 ',…”X。是N,而不是X,是X。如果列中有重复的名称,传入False将导致数据被覆盖。ReturnsDataFrame or dict of DataFramesDataFrame from the passed in Excel file. See notes in sheet_name argument for more information on when a dict of DataFrames is returned.DataFrame从传递的Excel文件。请参阅sheet_name参数中的注释,以获得关于何时返回数据变量的更多信息。