Py 's pandas : Pandas의 read_excel () 함수의 각 매개 변수에 대한 설명 및 함수 사용에 대한 설명

Py 's pandas : Pandas의 read_excel () 함수의 각 매개 변수에 대한 설명 및 함수 사용에 대한 설명

 

 

 

 

목차

Pandas의 read_excel () 함수의 각 매개 변수 설명 및 함수 사용 설명

read_excel () 함수 실현 함수

read_excel () 함수 사용 방법

1. 파일 이름을 문자열로 사용하거나 파일 개체를 열어 파일을 읽을 수 있습니다.

2. 색인과 헤더는 index_col과 헤더 매개 변수로 지정할 수 있습니다.

3. 열 유형이 유추되지만 명시 적으로 지정할 수 있습니다.

4. True, False 및 NA 값과 수천 개의 구분 기호에는 기본값이 있지만 명시 적으로 지정할 수도 있습니다. 원하는 값을 문자열 또는 문자열 목록으로 제공하십시오!

ead_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  Value
0   string1      1
1   string2      2
2  #Comment      3
pd.read_excel(open('tmp.xlsx', 'rb'),
              sheet_name='Sheet3')  
   Unnamed: 0      Name  Value
0           0   string1      1
1           1   string2      2
2           2  #Comment      3

 

2. 색인과 헤더는 index_col과 헤더 매개 변수로 지정할 수 있습니다.

pd.read_excel('tmp.xlsx', index_col=None, header=None)  
     0         1      2
0  NaN      Name  Value
1  0.0   string1      1
2  1.0   string2      2
3  2.0  #Comment      3

 

3. 열 유형이 유추되지만 명시 적으로 지정할 수 있습니다.

pd.read_excel('tmp.xlsx', index_col=0,
              dtype={'Name': str, 'Value': float})  
       Name  Value
0   string1    1.0
1   string2    2.0
2  #Comment    3.0

 

4. True, False 및 NA 값과 수천 개의 구분 기호에는 기본값이 있지만 명시 적으로 지정할 수도 있습니다. 원하는 값을 문자열 또는 문자열 목록으로 제공하십시오!

pd.read_excel('tmp.xlsx', index_col=0,
              na_values=['string1', 'string2'])  
       Name  Value
0       NaN      1
1       NaN      2
2  #Comment      3

 

 

ead_excel () 함수의 각 매개 변수에 대한 자세한 설명

공식 API : pandas.read_excel

def read_excel 찾을 위치 : 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, 수천 = None, comment = None, skipfooter = 0, convert_float = True, mangle_dupe_cols = True) :

나는

str, bytes, ExcelFile, xlrd.Book, 경로 객체 또는 파일 류 객체

유효한 문자열 경로가 허용됩니다. 문자열은 URL 일 수 있습니다. 유효한 URL 체계에는 http, ftp, s3 및 파일이 포함됩니다. 파일 URL의 경우 호스트가 필요합니다. 로컬 파일은 file : //localhost/path/to/table.xlsx 일 수 있습니다. 경로 객체를 전달하려는 경우 pandas는 모든 os.PathLike를 허용합니다. 파일 류 객체에 의해 우리는 파일 핸들러 (예 : 내장 된 열기 함수를 통해) 또는 StringIO와 같은 read () 메소드를 가진 객체를 참조합니다.

str, bytes, ExcelFile, xlrd.Book, 경로 객체, 또는 파일 류 객체

유효한 문자열 경로. 문자열은 URL이 될 수 있습니다. 유효한 URL 체계에는 http, ftp, s3 및 파일이 포함됩니다. 파일 URL의 경우 호스트가 필요합니다. 로컬 파일은 file : //localhost/path/to/table.xlsx 일 수 있습니다. 경로 객체를 전달하려는 경우 pandas는 os.path와 유사한 것을 허용합니다. 파일과 유사한 객체의 경우 read () 메서드를 사용하여 파일 핸들러 (예 : 내장 된 열기 함수를 통해) 또는 StringIO와 같은 객체를 참조합니다.

시트 _ 이름

str, int, list 또는 None, 기본값 0

시트 이름에는 문자열이 사용됩니다. 정수는 인덱스가 0 인 시트 위치에 사용됩니다. 문자열 / 정수 목록은 여러 시트를 요청하는 데 사용됩니다. 모든 시트를 가져 오려면 없음을 지정하십시오.

사용 가능한 사례 :

  • 기본값  0: 첫 번째 시트를 DataFrame으로

  • 1: DataFrame으로 두 번째 시트

  • "Sheet1": 이름이 "Sheet1"인 시트로드

  • [0, 1, "Sheet5"]: 첫 번째, 두 번째 및 "Sheet5"라는 이름의 시트를 DataFrame의 사전으로로드합니다.

  • 없음 : 모든 시트.

테이블 이름은 str, int, list 또는 None과 같은 기본 문자열 0을 사용합니다. 정수는 인덱스가 0 인 워크 시트 위치에 사용됩니다. 문자열 / 정수 목록은 여러 테이블을 요청하는 데 사용됩니다. 모든 테이블을 가져 오려면 없음을 지정하십시오. 가용성 : 기본값은 0 : 첫 번째 시트가 DataFrame1로 사용됨 : 두 번째 시트가 DataFrame "Sheet1"로 사용됨 : "Sheet1"이라는 테이블로드 [0,1, "Sheet5"] : 첫 번째, 두 번째 및 이름로드 "Sheet5"테이블은 DataFrameNone : 모든 테이블의 사전으로 사용됩니다.
헤더

int, int 목록, 기본값 0

구문 분석 된 DataFrame의 열 레이블에 사용할 행 (인덱싱 0)입니다. 정수 목록이 전달되면 해당 행 위치가  MultiIndex. 헤더가 없으면 None을 사용하십시오.

행 (0 인덱스), 구문 분석 된 데이터 형식의 열 레이블입니다. 정수 목록이 전달되면 이러한 행 위치가 다중 인덱스로 병합됩니다. 제목이 없으면 None이 사용됩니다.
이름

배열 유사, 기본값 없음

사용할 열 이름 목록입니다. 파일에 헤더 행이 없으면 명시 적으로 header = None을 전달해야합니다.

사용할 열 이름 목록입니다. 파일에 헤더 행이 없으면 header = None을 명시 적으로 전달해야합니다.

names 매개 변수를 사용하는 경우 이름 변경과 유사합니다. 모든 원본 데이터를 일치시키는 것을 잊지 마십시오 . 즉, 더 많거나 적지 않으며 더 많거나 적 으면 ValueError가 발생 합니다.

index_col

int, int 목록, 기본값 없음

DataFrame의 행 레이블로 사용할 열 (인덱싱 0)입니다. 그러한 열이 없으면 None을 전달하십시오. 목록이 전달되면 해당 열이  MultiIndex. 를 사용하여 데이터 하위 집합을 선택한  usecols경우 index_col은 하위 집합을 기반으로합니다.

열 (인덱스 0)은 데이터 형식의 행 레이블로 사용됩니다. 그러한 열이 없으면 None을 전달하십시오. 목록이 전달되면 이러한 열이 다중 인덱스로 병합됩니다. usecols를 사용하여 데이터 하위 집합을 선택한 경우 index_col은 해당 하위 집합을 기반으로합니다.

Usecols

int, str, list-like 또는 callable default None

  • None이면 모든 열을 구문 분석합니다.

  • 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参数指定要读入的列

squeeze

bool, default False

If the parsed data only contains one column then return a Series.

如果解析的数据只包含一列,则返回一个序列。
dtype

Type name or dict of column -> type, default None

Data 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转换。

engine

str, default None

If 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文件。
converters

dict, default None

Dict 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_values

list, default None

Values to consider as True.

true_values
false_values

list, default None

Values to consider as False.

false_values
skiprows

list-like

Rows to skip at the beginning (0-indexed).

开头要跳过的行(0索引)。
nrows

int, default None

Number of rows to parse.

New in version 0.23.0.

要解析的行数。

新版本0.23.0。

na_values

scalar, str, list-like, or dict, default None

Additional 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_na

bool, default True

Whether 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_filter

bool, default True

Detect 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可以提高读取大文件的性能。
verbose

bool, default False

Indicate number of NA values placed in non-numeric columns.

指示放置在非数字列中的NA值的数目。
parse_dates

bool, list-like, or dict, default False

The 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_parser

function, optional

Function 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一次。
thousands

str, default None

Thousands 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中是必要的,任何数值列都将自动解析,无论显示格式如何。

 

comment

str, default None

Comments 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.

注释掉行中的余数。向此参数传递一个或多个字符,以指示输入文件中的注释。注释字符串和当前行结束之间的任何数据都将被忽略。
skipfooter

int, default 0

Rows at the end to skip (0-indexed).

末尾要跳过的行(0索引)。

convert_float

bool, default True

Convert 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_cols

bool, default True

Duplicate 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将导致数据被覆盖。
Returns

DataFrame or dict of DataFrames

DataFrame 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参数中的注释,以获得关于何时返回数据变量的更多信息。

 

 

 

 

 

 

 

추천

출처blog.csdn.net/qq_41185868/article/details/108503572