Python酷库之旅-第三方库Pandas(009)
目录
一、用法精讲
19、pandas.read_xml函数
19-1、语法
19-2、参数
19-3、功能
19-4、返回值
19-5、说明
19-6、用法
19-6-1、数据准备
19-6-2、代码示例
19-6-3、结果输出
20、pandas.DataFrame.to_xml函数
20-1、语法
20-2、参数
20-3、功能
20-4、返回值
20-5、说明
20-6、用法
20-6-1、数据准备
20-6-2、代码示例
20-6-3、结果输出
21、pandas.DataFrame.to_latex函数
21-1、语法
21-2、参数
21-3、功能
21-4、返回值
21-5、说明
21-6、用法
21-6-1、数据准备
21-6-2、代码示例
21-6-3、结果输出
二、推荐阅读
1、Python筑基之旅
2、Python函数之旅
3、Python算法之旅
4、Python魔法之旅
5、博客个人主页
一、用法精讲
19、pandas.read_xml函数
19-1、语法
# 19、pandas.read_xml函数
pandas.read_xml(path_or_buffer, *, xpath='./*', namespaces=None, elems_only=False, attrs_only=False, names=None, dtype=None, converters=None, parse_dates=None, encoding='utf-8', parser='lxml', stylesheet=None, iterparse=None, compression='infer', storage_options=None, dtype_backend=_NoDefault.no_default)
Read XML document into a DataFrame object.New in version 1.3.0.Parameters:
path_or_bufferstr, path object, or file-like object
String, path object (implementing os.PathLike[str]), or file-like object implementing a read() function. The string can be any valid XML string or a path. The string can further be a URL. Valid URL schemes include http, ftp, s3, and file.Deprecated since version 2.1.0: Passing xml literal strings is deprecated. Wrap literal xml input in io.StringIO or io.BytesIO instead.xpathstr, optional, default ‘./*’
The XPath to parse required set of nodes for migration to DataFrame.``XPath`` should return a collection of elements and not a single element. Note: The etree parser supports limited XPath expressions. For more complex XPath, use lxml which requires installation.namespacesdict, optional
The namespaces defined in XML document as dicts with key being namespace prefix and value the URI. There is no need to include all namespaces in XML, only the ones used in xpath expression. Note: if XML document uses default namespace denoted as xmlns=’<URI>’ without a prefix, you must assign any temporary namespace prefix such as ‘doc’ to the URI in order to parse underlying nodes and/or attributes. For example,namespaces = {"doc": "https://example.com"}elems_onlybool, optional, default False
Parse only the child elements at the specified xpath. By default, all child elements and non-empty text nodes are returned.attrs_onlybool, optional, default False
Parse only the attributes at the specified xpath. By default, all attributes are returned.nameslist-like, optional
Column names for DataFrame of parsed XML data. Use this parameter to rename original element names and distinguish same named elements and attributes.dtypeType name or dict of column -> type, optional
Data type for data or columns. E.g. {‘a’: np.float64, ‘b’: np.int32, ‘c’: ‘Int64’} Use str or object together with suitable na_values settings to preserve and not interpret dtype. If converters are specified, they will be applied INSTEAD of dtype conversion.New in version 1.5.0.convertersdict, optional
Dict of functions for converting values in certain columns. Keys can either be integers or column labels.New in version 1.5.0.parse_datesbool or list of int or names or list of lists or dict, default False
Identifiers to parse index or columns to datetime. The behavior is as follows:boolean. 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’New in version 1.5.0.encodingstr, optional, default ‘utf-8’
Encoding of XML document.parser{‘lxml’,’etree’}, default ‘lxml’
Parser module to use for retrieval of data. Only ‘lxml’ and ‘etree’ are supported. With ‘lxml’ more complex XPath searches and ability to use XSLT stylesheet are supported.stylesheetstr, path object or file-like object
A URL, file-like object, or a raw string containing an XSLT script. This stylesheet should flatten complex, deeply nested XML documents for easier parsing. To use this feature you must have lxml module installed and specify ‘lxml’ as parser. The xpath must reference nodes of transformed XML document generated after XSLT transformation and not the original XML document. Only XSLT 1.0 scripts and not later versions is currently supported.iterparsedict, optional
The nodes or attributes to retrieve in iterparsing of XML document as a dict with key being the name of repeating element and value being list of elements or attribute names that are descendants of the repeated element. Note: If this option is used, it will replace xpath parsing and unlike xpath, descendants do not need to relate to each other but can exist any where in document under the repeating element. This memory- efficient method should be used for very large XML files (500MB, 1GB, or 5GB+). For example,iterparse = {"row_element": ["child_elem", "attr", "grandchild_elem"]}New in version 1.5.0.compressionstr or dict, default ‘infer’
For on-the-fly decompression of on-disk data. If ‘infer’ and ‘path_or_buffer’ is path-like, then detect compression from the following extensions: ‘.gz’, ‘.bz2’, ‘.zip’, ‘.xz’, ‘.zst’, ‘.tar’, ‘.tar.gz’, ‘.tar.xz’ or ‘.tar.bz2’ (otherwise no compression). If using ‘zip’ or ‘tar’, the ZIP file must contain only one data file to be read in. Set to None for no decompression. Can also be a dict with key 'method' set to one of {'zip', 'gzip', 'bz2', 'zstd', 'xz', 'tar'} and other key-value pairs are forwarded to zipfile.ZipFile, gzip.GzipFile, bz2.BZ2File, zstandard.ZstdDecompressor, lzma.LZMAFile or tarfile.TarFile, respectively. As an example, the following could be passed for Zstandard decompression using a custom compression dictionary: compression={'method': 'zstd', 'dict_data': my_compression_dict}.New in version 1.5.0: Added support for .tar files.Changed in version 1.4.0: Zstandard support.storage_optionsdict, optional
Extra options that make sense for a particular storage connection, e.g. host, port, username, password, etc. For HTTP(S) URLs the key-value pairs are forwarded to urllib.request.Request as header options. For other URLs (e.g. starting with “s3://”, and “gcs://”) the key-value pairs are forwarded to fsspec.open. Please see fsspec and urllib for more details, and for more examples on storage options refer here.dtype_backend{‘numpy_nullable’, ‘pyarrow’}, default ‘numpy_nullable’
Back-end data type applied to the resultant DataFrame (still experimental). Behaviour is as follows:"numpy_nullable": returns nullable-dtype-backed DataFrame (default)."pyarrow": returns pyarrow-backed nullable ArrowDtype DataFrame.New in version 2.0.Returns:
df
A DataFrame.
19-2、参数
19-2-1、path_or_buffer(必须):字符串或文件对象,表示XML文件的路径或文件对象,用于指定要读取的XML数据源。
19-2-2、xpath(可选,默认值为'./'):字符串或列表的字符串,用于选择XML文件中感兴趣的元素。默认为'./*',表示选择XML文档根元素下的所有子元素,你可以使用XPath表达式来精确定位你想要的数据。
19-2-3、namespaces(可选,默认值为None):字典,用于定义XML命名空间。如果XML文档使用了命名空间,你可能需要在这里指定它们,以便正确解析XPath表达式。
19-2-4、elems_only(可选,默认值为False):布尔值,如果为True,则只解析XML中的元素节点(element nodes),忽略属性和文本节点。
19-2-5、attrs_only(可选,默认值为False):布尔值,如果为True,则只解析元素的属性(attributes),忽略元素本身的文本内容。
19-2-6、names(可选,默认值为None):列表或字典,用于指定DataFrame的列名。如果提供列表,则列名将按顺序与解析出的元素或属性匹配;如果提供字典,则可以使用XPath表达式作为键来映射到列名。
19-2-7、dtype(可选,默认值为None):单个类型或类型字典,用于指定DataFrame列的数据类型。如果提供单个类型,则所有列都将被转换为该类型;如果提供字典,则可以使用列名作为键来指定每列的数据类型。
19-2-8、converters(可选,默认值为None):字典,允许你指定用于将字符串转换为其他Python类型的函数,键是列名,值是转换函数。
19-2-9、parse_dates(可选,默认值为None):布尔值、列表或字典,用于指定哪些列应该被解析为日期时间类型。如果为True,则尝试解析所有列;如果为列表,则指定列名列表;如果为字典,则可以通过字典的键来指定列名,并通过字典的值来指定日期时间的格式。
19-2-10、encoding(可选,默认值为'utf-8'):字符串,指定文件的编码方式。
19-2-11、parser(可选,默认值为'lxml'):字符串,指定用于解析XML的库。其他选项可能包括 'xml.etree.ElementTree'(简称 'etree'),但'lxml'通常更快更灵活。
19-2-12、stylesheet(可选,默认值为None):目前此参数在pandas中不常用或未直接支持,可能用于未来版本或特定扩展中。
19-2-13、iterparse(可选,默认值为None):布尔值或整数,用于控制是否使用迭代解析来减少内存使用。如果为True,则使用lxml的iterparse功能;如果为整数,则指定tag和attrib的内存使用限制(以MB为单位)。
19-2-14、compression(可选,默认值为'infer'):字符串或None,用于指定文件的压缩方式,如 'gzip', 'bz2', 'zip', 'xz' 或 'infer'(自动检测)。
19-2-15、storage_options(可选,默认值为None):字典,提供对存储在远程或虚拟文件系统上的文件的访问选项,这对于读取如AWS S3、Google Cloud Storage等云存储上的文件特别有用。
19-2-16、dtype_backend(可选):内部使用,通常不需要用户设置。
19-3、功能
将XML数据解析为pandas DataFrame对象,使得XML数据的读取和处理变得更加方便和高效。
19-4、返回值
一个pandas DataFrame对象,其中包含了从XML数据中解析出的结构化数据。
19-5、说明
pandas.read_xml函数的具体参数和行为可能会随着pandas版本的更新而发生变化,因此,建议用户在使用该函数时查阅最新的pandas文档,以获取最准确的信息和示例。
19-6、用法
19-6-1、数据准备
# 19、pandas.read_xml函数
# 19-1、创建xml文件example.xml
import pandas as pd
import xml.etree.ElementTree as ET
# 准备数据
data = {'id': ['bk101', 'bk102'],'author': ['Gambardella, Matthew', 'Ralls, Kim'],'title': ['XML Developer\'s Guide', 'Midnight Rain'],'genre': ['Computer', 'Fantasy'],'price': [44.95, 5.95],'publish_date': ['2000-10-01', '2000-12-16'],'description': ['An in-depth look at creating applications with XML.','A former architect battles corporate zombies, an evil sorceress, and her own childhood to become queen of the world.']
}
df = pd.DataFrame(data)
# 创建 XML 文档的根元素,包括命名空间
catalog = ET.Element('catalog', {'xmlns:bk': 'http://example.com/books'})
# 遍历DataFrame,为每个book创建一个元素
for index, row in df.iterrows():book = ET.SubElement(catalog, 'bk:book', {'id': row['id']})# 添加子元素for field in ['author', 'title', 'genre', 'price', 'publish_date', 'description']:elem = ET.SubElement(book, field)elem.text = str(row[field])
# 将XML树写入文件
tree = ET.ElementTree(catalog)
with open('example.xml', 'wb') as f:tree.write(f, encoding='utf-8', xml_declaration=True)
print('XML文件已创建!')
19-6-2、代码示例
# 19、pandas.read_xml函数
# 19-2、读取XML文件
import pandas as pd
# 指定XML文件路径
file_path = 'example.xml'
# 定义命名空间字典
namespaces = {'bk': 'http://example.com/books'}
# 读取XML文件
try:# 使用pandas.read_xml读取XML文件df = pd.read_xml(path_or_buffer=file_path,xpath='.//bk:book', # 使用XPath表达式选择book元素namespaces=namespaces, # 传递命名空间字典dtype={'price': float}, # 指定数据类型转换parse_dates=['publish_date'], # 解析日期列encoding='utf-8', # 指定编码)# 显示DataFrameprint(df)
except FileNotFoundError:print(f"文件 {file_path} 未找到!")
except Exception as e:print(f"读取XML文件时发生错误: {e}")
19-6-3、结果输出
# 19-2、读取XML文件
# id ... description
# 0 bk101 ... An in-depth look at creating applications with...
# 1 bk102 ... A former architect battles corporate zombies, ...
#
# [2 rows x 7 columns]
20、pandas.DataFrame.to_xml函数
20-1、语法
# 20、pandas.DataFrame.to_xml函数
DataFrame.to_xml(path_or_buffer=None, *, index=True, root_name='data', row_name='row', na_rep=None, attr_cols=None, elem_cols=None, namespaces=None, prefix=None, encoding='utf-8', xml_declaration=True, pretty_print=True, parser='lxml', stylesheet=None, compression='infer', storage_options=None)
Render a DataFrame to an XML document.New in version 1.3.0.Parameters:
path_or_bufferstr, path object, file-like object, or None, default None
String, path object (implementing os.PathLike[str]), or file-like object implementing a write() function. If None, the result is returned as a string.indexbool, default True
Whether to include index in XML document.root_namestr, default ‘data’
The name of root element in XML document.row_namestr, default ‘row’
The name of row element in XML document.na_repstr, optional
Missing data representation.attr_colslist-like, optional
List of columns to write as attributes in row element. Hierarchical columns will be flattened with underscore delimiting the different levels.elem_colslist-like, optional
List of columns to write as children in row element. By default, all columns output as children of row element. Hierarchical columns will be flattened with underscore delimiting the different levels.namespacesdict, optional
All namespaces to be defined in root element. Keys of dict should be prefix names and values of dict corresponding URIs. Default namespaces should be given empty string key. For example,namespaces = {"": "https://example.com"}prefixstr, optional
Namespace prefix to be used for every element and/or attribute in document. This should be one of the keys in namespaces dict.encodingstr, default ‘utf-8’
Encoding of the resulting document.xml_declarationbool, default True
Whether to include the XML declaration at start of document.pretty_printbool, default True
Whether output should be pretty printed with indentation and line breaks.parser{‘lxml’,’etree’}, default ‘lxml’
Parser module to use for building of tree. Only ‘lxml’ and ‘etree’ are supported. With ‘lxml’, the ability to use XSLT stylesheet is supported.stylesheetstr, path object or file-like object, optional
A URL, file-like object, or a raw string containing an XSLT script used to transform the raw XML output. Script should use layout of elements and attributes from original output. This argument requires lxml to be installed. Only XSLT 1.0 scripts and not later versions is currently supported.compressionstr or dict, default ‘infer’
For on-the-fly compression of the output data. If ‘infer’ and ‘path_or_buffer’ is path-like, then detect compression from the following extensions: ‘.gz’, ‘.bz2’, ‘.zip’, ‘.xz’, ‘.zst’, ‘.tar’, ‘.tar.gz’, ‘.tar.xz’ or ‘.tar.bz2’ (otherwise no compression). Set to None for no compression. Can also be a dict with key 'method' set to one of {'zip', 'gzip', 'bz2', 'zstd', 'xz', 'tar'} and other key-value pairs are forwarded to zipfile.ZipFile, gzip.GzipFile, bz2.BZ2File, zstandard.ZstdCompressor, lzma.LZMAFile or tarfile.TarFile, respectively. As an example, the following could be passed for faster compression and to create a reproducible gzip archive: compression={'method': 'gzip', 'compresslevel': 1, 'mtime': 1}.New in version 1.5.0: Added support for .tar files.Changed in version 1.4.0: Zstandard support.storage_optionsdict, optional
Extra options that make sense for a particular storage connection, e.g. host, port, username, password, etc. For HTTP(S) URLs the key-value pairs are forwarded to urllib.request.Request as header options. For other URLs (e.g. starting with “s3://”, and “gcs://”) the key-value pairs are forwarded to fsspec.open. Please see fsspec and urllib for more details, and for more examples on storage options refer here.Returns:
None or str
If io is None, returns the resulting XML format as a string. Otherwise returns None.
20-2、参数
20-2-1、path_or_buffer(可选,默认值为None):指定输出XML文件的路径或文件对象,如果为None(默认值),则返回一个字符串形式的XML。
20-2-2、index(可选,默认值为True):是否将DataFrame的索引作为属性或子元素包含在输出的XML中。如果为True,则索引会被包含;如果为False,则不会。
20-2-3、root_name(可选,默认值为'data'):输出的XML文件的根元素的名称。
20-2-4、row_name(可选,默认值为'row'):DataFrame中每一行对应的XML元素的名称。
20-2-5、na_rep(可选,默认值为None):用于替换DataFrame中缺失值(NaN)的字符串。如果为None(默认值),则缺失值不会被特别处理,可能会以空元素或其他形式出现(取决于其他参数)。
20-2-6、attr_cols(可选,默认值为None):指定哪些列的值应该作为XML元素的属性而不是子元素。如果为None(默认值),则所有列都会作为子元素。
20-2-7、elem_cols(可选,默认值为None):指定哪些列的值应该作为XML元素的子元素,这个参数与attr_cols互补,用于明确哪些列应该被处理为元素属性之外的内容。如果为None(默认值),则没有特定的限制。
20-2-8、namespaces(可选,默认值为None):自定义的命名空间字典,用于为XML元素添加命名空间,字典的键是命名空间的前缀,值是命名空间的URI。
20-2-9、prefix(可选,默认值为None):如果设置了命名空间,则此参数指定默认命名空间的前缀。
20-2-10、encoding(可选,默认值为'utf-8'):输出XML文件的编码方式。
20-2-11、xml_declaration(可选,默认值为True):是否在XML文件的开头包含XML声明(<?xml version="1.0" encoding="utf-8"?>)。
20-2-12、pretty_print(可选,默认值为True):是否以易于阅读的格式(即缩进和换行)输出XML。如果为False,则输出会是一行紧凑的代码。
20-2-13、parser(可选,默认值为'lxml'):用于解析和生成XML的库。'lxml'通常比'xml.etree.ElementTree'更快且功能更强大,但后者是Python标准库的一部分。
20-2-14、stylesheet(可选,默认值为None):可选的XSL样式表路径,用于在浏览器中查看XML时应用样式。
20-2-15、compression(可选,默认值为'infer'):仅在写入文件时有效,指定用于输出文件的压缩类型,'infer'会根据文件扩展名自动选择压缩方式。
20-2-16、storage_options(可选,默认值为None):额外的参数,用于传递给底层存储系统(如 s3fs、gcsfs 等),用于控制存储细节。
20-3、功能
将pandas DataFrame对象转换为XML格式的数据,并可以选择性地将其保存到文件或返回为字符串。
20-4、返回值
关于返回值,这取决于path_or_buffer参数的值:
20-4-1、如果path_or_buffer是一个文件路径(字符串或pathlib.Path对象)或可写入的文件对象,则to_xml()函数不会返回任何值(即返回None),而是将XML数据写入指定的文件。
20-4-2、如果path_or_buffer是None,则to_xml()函数会返回一个字符串,该字符串包含了DataFrame的XML表示。
20-5、说明
该函数为数据分析师和科学家提供了一种方便的方法来将DataFrame的内容导出为XML,以便与需要XML格式数据的系统或应用程序进行交互。
20-6、用法
20-6-1、数据准备
无
20-6-2、代码示例
# 20、pandas.DataFrame.to_xml函数
import pandas as pd
# 创建示例DataFrame
data = {'id': ['bk101', 'bk102'],'author': ['Gambardella, Matthew', 'Ralls, Kim'],'title': ["XML Developer's Guide", 'Midnight Rain'],'genre': ['Computer', 'Fantasy'],'price': [44.95, 5.95],'publish_date': ['2024-7-11', '2024-7-7'],'description': ['An in-depth look at creating applications with XML.','A former architect battles corporate zombies, an evil sorceress, and her own childhood to become queen of the world.']
}
df = pd.DataFrame(data)
# 定义XML文件保存路径
xml_file_path = 'output.xml'
# 将DataFrame保存为XML文件
try:df.to_xml(path_or_buffer=xml_file_path,index=False, # 不保存索引列root_name='catalog', # 根元素名称row_name='book', # 行元素名称na_rep='N/A', # 替换缺失值的字符串encoding='utf-8', # 文件编码xml_declaration=True, # 包含XML声明pretty_print=True # 美化输出)print(f"DataFrame成功保存为XML文件:{xml_file_path}")
except Exception as e:print(f"保存DataFrame为XML文件时发生错误: {e}")
20-6-3、结果输出
执行上述代码后,生成的output.xml文件内容将类似于:
21、pandas.DataFrame.to_latex函数
21-1、语法
# 21、pandas.DataFrame.to_latex函数
DataFrame.to_latex(buf=None, *, columns=None, header=True, index=True, na_rep='NaN', formatters=None, float_format=None, sparsify=None, index_names=True, bold_rows=False, column_format=None, longtable=None, escape=None, encoding=None, decimal='.', multicolumn=None, multicolumn_format=None, multirow=None, caption=None, label=None, position=None)
Render object to a LaTeX tabular, longtable, or nested table.Requires \usepackage{{booktabs}}. The output can be copy/pasted into a main LaTeX document or read from an external file with \input{{table.tex}}.Changed in version 2.0.0: Refactored to use the Styler implementation via jinja2 templating.Parameters:
bufstr, Path or StringIO-like, optional, default None
Buffer to write to. If None, the output is returned as a string.columnslist of label, optional
The subset of columns to write. Writes all columns by default.headerbool or list of str, default True
Write out the column names. If a list of strings is given, it is assumed to be aliases for the column names.indexbool, default True
Write row names (index).na_repstr, default ‘NaN’
Missing data representation.formatterslist of functions or dict of {{str: function}}, optional
Formatter functions to apply to columns’ elements by position or name. The result of each function must be a unicode string. List must be of length equal to the number of columns.float_formatone-parameter function or str, optional, default None
Formatter for floating point numbers. For example float_format="%.2f" and float_format="{{:0.2f}}".format will both result in 0.1234 being formatted as 0.12.sparsifybool, optional
Set to False for a DataFrame with a hierarchical index to print every multiindex key at each row. By default, the value will be read from the config module.index_namesbool, default True
Prints the names of the indexes.bold_rowsbool, default False
Make the row labels bold in the output.column_formatstr, optional
The columns format as specified in LaTeX table format e.g. ‘rcl’ for 3 columns. By default, ‘l’ will be used for all columns except columns of numbers, which default to ‘r’.longtablebool, optional
Use a longtable environment instead of tabular. Requires adding a usepackage{{longtable}} to your LaTeX preamble. By default, the value will be read from the pandas config module, and set to True if the option styler.latex.environment is “longtable”.Changed in version 2.0.0: The pandas option affecting this argument has changed.escapebool, optional
By default, the value will be read from the pandas config module and set to True if the option styler.format.escape is “latex”. When set to False prevents from escaping latex special characters in column names.Changed in version 2.0.0: The pandas option affecting this argument has changed, as has the default value to False.encodingstr, optional
A string representing the encoding to use in the output file, defaults to ‘utf-8’.decimalstr, default ‘.’
Character recognized as decimal separator, e.g. ‘,’ in Europe.multicolumnbool, default True
Use multicolumn to enhance MultiIndex columns. The default will be read from the config module, and is set as the option styler.sparse.columns.Changed in version 2.0.0: The pandas option affecting this argument has changed.multicolumn_formatstr, default ‘r’
The alignment for multicolumns, similar to column_format The default will be read from the config module, and is set as the option styler.latex.multicol_align.Changed in version 2.0.0: The pandas option affecting this argument has changed, as has the default value to “r”.multirowbool, default True
Use multirow to enhance MultiIndex rows. Requires adding a usepackage{{multirow}} to your LaTeX preamble. Will print centered labels (instead of top-aligned) across the contained rows, separating groups via clines. The default will be read from the pandas config module, and is set as the option styler.sparse.index.Changed in version 2.0.0: The pandas option affecting this argument has changed, as has the default value to True.captionstr or tuple, optional
Tuple (full_caption, short_caption), which results in \caption[short_caption]{{full_caption}}; if a single string is passed, no short caption will be set.labelstr, optional
The LaTeX label to be placed inside \label{{}} in the output. This is used with \ref{{}} in the main .tex file.positionstr, optional
The LaTeX positional argument for tables, to be placed after \begin{{}} in the output.Returns:
str or None
If buf is None, returns the result as a string. Otherwise returns None.
21-2、参数
21-2-1、buf(可选,默认值为None):缓冲区或路径(字符串或文件对象),用于写入生成的LaTeX表格,如果为None,则输出为一个字符串。
21-2-2、columns(可选,默认值为None):要包括的列名列表,如果为None,则包括所有列。
21-2-3、header(可选,默认值为True):是否写入列名作为表头。
21-2-4、index(可选,默认值为True):是否写入行索引(标签)作为一列。
21-2-5、na_rep(可选,默认值为'NaN'):用于表示缺失值的字符串。
21-2-6、formatters(可选,默认值为None):一个单元素或元素列表的字典,用于格式化列的值,键是列名,值是格式化函数。
21-2-7、float_format(可选,默认值为None):字符串,用于格式化浮点数的格式说明符(如'%.2f' 表示保留两位小数)。
21-2-8、sparsify(可选,默认值为None):已弃用,不建议使用。
21-2-9、index_names(可选,默认值为True):如果为True,并且index为True,则打印索引的名称(默认为 'index');如果MultiIndex,则打印每个级别的名称。
21-2-10、bold_rows(可选,默认值为False):如果为True,则为每个<tr>元素添加\bfseries标签,使其加粗。注意,这可能会与LaTeX文档的其余部分在样式上不一致。
21-2-11、column_format(可选,默认值为None):一个单字符串或字符串列表,指定每列的格式。例如,'lrc'表示第一列左对齐,第二列居中对齐,第三列右对齐。如果为单个字符串,则所有列使用相同的格式。
21-2-12、longtable(可选,默认值为None):{'all', None, 'firstpage', 'firstrow', 'none'} 或布尔值。如果为True或'all',则使用longtable环境代替tabular环境,这允许表格跨越多页,其他选项控制longtable的某些特性。
21-2-13、escape(可选,默认值为None):用于转义LaTeX字符串的函数或布尔值,如果为None,则默认转义;如果为False,则不转义;如果为函数,则使用该函数进行转义。
21-2-14、encoding(可选,默认值为None):如果buf是一个文件对象,则忽略此参数;否则,指定输出字符串的编码。
21-2-15、decimal(可选,默认值为'.'):用于识别小数点的字符。
21-2-16、multicolumn(可选,默认值为None):布尔值或整数序列。如果为True,则尝试合并多个具有相同内容的列;如果为整数序列,则指定要合并的列索引。
21-2-17、multicolumn_format(可选,默认值为None):当multicolumn为True时,指定合并列的格式,默认为'c'(居中对齐)。
21-2-18、multirow(可选,默认值为None):目前pandas的to_latex()方法可能不直接支持multirow 参数,这通常需要在生成的LaTeX代码中手动处理或使用其他LaTeX工具。,
21-2-19、caption(可选,默认值为None):表格的标题字符串。如果提供,则会在LaTeX表格上方添加一个\caption{}命令。
21-2-20、label(可选,默认值为None):表格的标签字符串。如果提供,则会在LaTeX表格上方添加一个\label{}命令,便于在文档中引用。
21-2-21、position(可选,默认值为None):字符串,指定表格在LaTeX文档中的位置(如 'h'、't'、'b'、'p' 等)。然而,请注意,pandas.DataFrame.to_latex() 方法本身并不直接控制LaTeX表格的最终位置,这通常由LaTeX文档的其余部分和编译过程决定。
21-3、功能
将Pandas的DataFrame对象转换成LaTeX表格的代码。
21-4、返回值
函数的返回值取决于buf参数的值:
21-4-1、如果buf是None(默认值),则函数返回一个包含LaTeX表格代码的字符串,这个字符串可以直接在LaTeX文档中作为代码块使用,或者通过其他方式(如写入文件)进行进一步处理。
21-4-2、如果buf是一个文件对象(比如通过open()函数打开的文件)或是一个文件路径(字符串),则LaTeX表格代码会被写入到指定的文件或文件路径中,在这种情况下,函数不会返回任何值(即返回None)。
21-5、说明
该函数对于在学术论文、报告或任何需要高质量表格的LaTeX文档中嵌入数据表格非常有用。
21-6、用法
21-6-1、数据准备
无
21-6-2、代码示例
# 21、pandas.DataFrame.to_latex函数
import pandas as pd
# 创建示例DataFrame
data = {'id': ['bk101', 'bk102'],'author': ['Gambardella, Matthew', 'Ralls, Kim'],'title': ["XML Developer's Guide", 'Midnight Rain'],'genre': ['Computer', 'Fantasy'],'price': [44.95, 5.95],'publish_date': ['2024-7-1', '2024-7-7'],'description': ['An in-depth look at creating applications with XML.','A former architect battles corporate zombies, an evil sorceress, and her own childhood to become queen of the world.']
}
df = pd.DataFrame(data)
# 定义LaTeX文件保存路径
latex_file_path = 'output.tex'
# 将DataFrame转换为LaTeX表格格式并保存到文件
try:with open(latex_file_path, 'w', encoding='utf-8') as f:df.to_latex(buf=f,columns=['id', 'author', 'title', 'genre', 'price', 'publish_date', 'description'],header=True,index=False,na_rep='NaN',float_format="%.2f",sparsify=True, # 实际上在这个例子中不会生效index_names=False, # 因为没有索引bold_rows=False,caption='Books DataFrame',label='tab:books',escape=True)print(f"DataFrame成功保存为LaTeX文件:{latex_file_path}")
except Exception as e:print(f"保存DataFrame为LaTeX文件时发生错误 {e}")
21-6-3、结果输出
执行上述代码后,生成的output.tex文件内容将类似于
# \begin{table}
# \centering
# \caption{Books DataFrame}
# \label{tab:books}
# \begin{tabular}{lllllll}
# \hline
# id & author & title & genre & price & publish\_date & description \\
# \hline
# bk101 & Gambardella, Matthew & XML Developer's Guide & Computer & 44.95 & 2024-7-1 & An in-depth look at creating applications with XML. \\
# bk102 & Ralls, Kim & Midnight Rain & Fantasy & 5.95 & 2024-7-7 & A former architect battles corporate zombies, an evil sorceress, and her own childhood to become queen of the world. \\
# \hline
# \end{tabular}
# \end{table}
二、推荐阅读
1、Python筑基之旅
2、Python函数之旅
3、Python算法之旅
4、Python魔法之旅
5、博客个人主页
相关文章:

Python酷库之旅-第三方库Pandas(009)
目录 一、用法精讲 19、pandas.read_xml函数 19-1、语法 19-2、参数 19-3、功能 19-4、返回值 19-5、说明 19-6、用法 19-6-1、数据准备 19-6-2、代码示例 19-6-3、结果输出 20、pandas.DataFrame.to_xml函数 20-1、语法 20-2、参数 20-3、功能 20-4、返回值 …...

VPN 的入门介绍
VPN(虚拟专用网络) 简介 虚拟专用网络,简称虚拟专网(VPN),其主要功能是在公用网络上建立专用网络,进行加密通讯。在企业网络中有广泛应用。VPN网关通过对数据包的加密和数据包目标地址的转换实…...

移动UI: 什么特征会被认为是简洁风格,用案例告诉你
什么是简洁风格,恐怕一百个人有一百个是理解,本文通过理论分析案例的方式进行探讨。 移动 UI 中的简洁风格通常具有以下几个特征: 1. 平面化设计: 简洁风格的移动 UI 善于运用平面化设计,即去除过多的阴影、渐变和立…...

除了伦敦外,英国还有这些热门留学城市
在同学们选择出国留学时,首先要考虑到的便是择校的问题。除了排名、专业、录取要求之外,城市因素也占据了很大比重。 抛开学校自身的优势外,一座城市的氛围、成本、环境都是需要考虑的因素。下面就我们来盘点一下英国热门的留学城市。 爱丁…...

2390. 从字符串中移除星号
2390. 从字符串中移除星号 题目链接:2390. 从字符串中移除星号 代码如下: class Solution { public:string removeStars(string s) {vector<char> sta;for(int i0;i<s.size();i){if(s[i]*) {sta.pop_back();}else {sta.push_back(s[i])…...

UNION、UNION ALL、INTERSECT、MINUS
UNION、UNION ALL、INTERSECT、MINUS? 说明 UNION:对两个结果集进行并集操作,不包括重复行,同时进行默认规则的排序;IUNION ALL:对两个结果集进行并集操作,包括重复行,不进行排序&am…...

Perl 语言开发(九):深入探索Perl语言的文件处理
目录 1. 文件打开与关闭 1.1 打开文件 1.2 关闭文件 2. 读取文件内容 2.1 逐行读取 2.2 一次性读取整个文件 3. 写入文件内容 3.1 覆盖写入 3.2 追加写入 4. 文件测试操作 4.1 文件测试运算符 5. 文件路径操作 5.1 文件路径处理模块 5.2 获取文件路径信息 6. 文…...

稀疏之美:在Mojo模型中实现特征的稀疏表示
稀疏之美:在Mojo模型中实现特征的稀疏表示 在机器学习领域,特征的稀疏表示是一种高效的数据编码方式,尤其适用于具有大量特征和缺失值的数据集。稀疏表示使用特殊的数据结构来存储和处理数据,从而减少内存占用和提高计算效率。Mo…...

如何大幅减少 Vue.js 中的包大小和加载时间,提升用户体验!
大家好,我是CodeQi! 一位热衷于技术分享的码仔。 你知道吗,根据Google 的一项研究,如果网站加载时间超过 3 秒,53% 的移动用户会离开该网站? 性能优化是一个经常讨论的话题,但很多开发人员并不关心提高应用的速度。 在前端开发中,优化包大小和加载时间对于提升用户体…...

性能测试相关理解---性能测试流程(二)
六、性能测试流程(如何做性能测试?) 根据学习全栈测试博主的课程做的笔记 1、前期准备– 项目初期就开始,业务需求评审时尽量参与,对业务更深刻的认识(确定哪些是核心业务、哪些可能存在并发请求、确定什么地方会出现瓶颈,方便后…...

GD32 MCU ADC采样率如何计算?
大家在使用ADC采样的时候是否计算过ADC的采样率,这个问题非常关键! 以下为GD32F303系列MCU中有关ADC的参数,其中ADC时钟最大值为40MHz,12位分辨率下最大采样率为2.86MSPS.如果ADC时钟超频的话,可能会造成ADC采样异常&…...

.mkp勒索病毒:深度解析与防范
引言: 在数字化时代,网络安全问题日益严峻,其中勒索病毒作为一种极具破坏性的恶意软件,严重威胁着个人用户和企业机构的数据安全。在众多勒索病毒家族中,.mkp勒索病毒以其强大的加密能力和广泛的传播方式,成…...

5.opencv深浅拷贝
图像处理的复制操作 深浅拷贝 图像复制分成两种,第一种假复制,从原图片选择一部分图片拿出来观察,此时新生成的图片和原图实际上是同一张图片,即浅拷贝 将图片的一部分复制下来,放到新的内存中,即两张完全…...

C++11中新特性介绍-之(二)
11.自动类型推导 (1) auto类型自动推导 auto自动推导变量的类型 auto并不代表某个实际的类型,只是一个类型声明的占位符 auto并不是万能的在任意场景下都能推导,使用auto声明的变量必须进行初始化,以让编译器推导出它的实际类型,…...

STM32实现看门狗(HAL库)
文章目录 一. 看门狗1. 独立看门狗(IWDG)1.1 原理1.2 相关配置1.3 相关函数 2. 窗口看门狗(WWDG)2.1 原理2.2 相关配置2.3 相关函数 一. 看门狗 单片机在日常工作中常常会因为用户配置代码出现BUG,而导致芯片无法正常工…...

【漏洞复现】网络摄像头——弱口令
声明:本文档或演示材料仅供教育和教学目的使用,任何个人或组织使用本文档中的信息进行非法活动,均与本文档的作者或发布者无关。 文章目录 漏洞描述漏洞复现其他补充 漏洞描述 主流网络摄像头存在弱口令。 漏洞复现 JAWS 1)信息…...

视觉图像面积计算
在图像处理和计算机视觉中,计算对象面积的常见方法有两种:使用四邻域标记算法和使用轮廓计算。每种方法在不同情况下有各自的优缺点。 四邻域标记算法: 优点: 简单易实现。能够处理带有孔洞的复杂区域(只要孔洞不影响连…...

Vue笔记10-其它Composition API
shallowReactive与shallowRef shallow:浅的,和deep相反 shallowReactive:只处理对象最外层属性的响应式 shallowRef:只处理基本数据类型的响应式,不进行对象的响应式处理 如果有一个对象数据,结构比较深&a…...

AI集成工具平台一站式体验,零门槛使用国内外主流大模型
目录 0 写在前面1 AI艺术大师1.1 绘画制图1.2 智能作曲 2 AI科研助理2.1 学术搜索2.2 自动代码 3 AI智能对话3.1 聊天机器人3.2 模型竞技场 4 特别福利 0 写在前面 人工智能大模型浪潮滚滚,正推动着千行百业的数智化进程。随着技术演进,2024年被视为是大…...

北京交通大学学报
《北京交通大学学报》是经新闻出版广电总局批准,由教育部主管,北京交通大学主办的自然科学理论与技术类学术期刊。学报致力于全面反映交通运输和信息与通信领域相关学科的最新研究进展。主要刊登交通运输工程、系统科学、信息与通信工程、控制科学与工程…...

【LinuxC语言】手撕Http之处理POST请求
文章目录 前言声明POST的组成读取POST信息读取消息体长度读取消息体解析消息体How to use?总结前言 在互联网的世界中,HTTP协议无疑是最重要的协议之一。它是Web的基础,支持着我们日常生活中的大部分在线活动。尽管有许多现成的库可以处理HTTP请求,但了解其底层工作原理是…...

以软件定义推动智算中心建设
2024 年 6 月 27 日,由益企研究院和 CDCC 主办、OCTC 开放计算委员会协办、隆高展览承办的"2024 中国智算中心全栈技术大会、第 5 届中国数据中心绿色能源大会暨第 10 届中国(上海)国际数据中心产业展览会”在上海圆满结束。本次大会以&…...

Apache Seata分布式事务原理解析探秘
本文来自 Apache Seata官方文档,欢迎访问官网,查看更多深度文章。 本文来自 Apache Seata官方文档,欢迎访问官网,查看更多深度文章。 前言 fescar发布已有时日,分布式事务一直是业界备受关注的领域,fesca…...

MySQL-18-mysql source 执行 sql 文件时中文乱码
拓展阅读 MySQL 00 View MySQL 01 Ruler mysql 日常开发规范 MySQL 02 truncate table 与 delete 清空表的区别和坑 MySQL 03 Expression 1 of ORDER BY clause is not in SELECT list,references column MySQL 04 EMOJI 表情与 UTF8MB4 的故事 MySQL 05 MySQL入门教程&a…...

flutter环境安装(Mac+vscode)
以前据说flutter跨平台开发app很牛逼,最近突然想到这个东西,于是想体验一下flutter的开发流程,看看能否适合做独立开发。 我用的是mac,手机也是ios,就开始着手部署mac下的开发环境了。 开发后台的时候,一…...

【题解】—— LeetCode一周小结27
🌟欢迎来到 我的博客 —— 探索技术的无限可能! 🌟博客的简介(文章目录) 【题解】—— 每日一道题目栏 上接:【题解】—— LeetCode一周小结26 2024.7 1.最大化一张图中的路径价值 题目链接:…...

C++后端开发--网络编程基础
目录 一、网络编程基础概念 1.1 网络协议 1.2 IP地址和端口号 1.3 Socket 1.4 TCP协议的三次握手和四次挥手 TCP的三次握手 TCP的四次挥手 整个流程更通俗易懂 TCP 三次握手流程图 TCP 四次挥手流程图 1.5 详细介绍一下http协议 HTTP协议的主要特点 HTTP请求 HTT…...

如何将资源前端通过 Docker 部署到远程服务器
作为一个程序员,在开发过程中,经常会遇到项目部署的问题,在现在本就不稳定的大环境下,前端开发也需要掌握部署技能,来提高自己的生存力,今天就详细说一下如何把一个前端资源放到远程服务器上面通过docker部…...

@react-google-maps/api实现谷歌地图嵌入React项目中,并且做到点击地图任意一处,获得它的经纬度
1.第一步要加入项目package.json中或者直接yarn install它都可以 "react-google-maps/api": "^2.19.3",2.加入项目中 import AMapLoader from amap/amap-jsapi-loader;import React, { PureComponent } from react; import { GoogleMap, LoadScript, Mar…...

【MySQL】2.库的操作
库的操作 一.创建数据库1.数据库的编码集 二.查看数据库三.修改数据库四.删除数据库五.数据库的备份和恢复 一.创建数据库 create database [if not exists] db_name [charsetutf8] [collateutf8_general_ci] //创建一个名为db_name的数据库,本质就是在/var/lib/my…...