Python酷库之旅-第三方库Pandas(013)

目录

一、用法精讲

31、pandas.read_feather函数

31-1、语法

31-2、参数

31-3、功能

31-4、返回值

31-5、说明

31-6、用法

31-6-1、数据准备

31-6-2、代码示例

31-6-3、结果输出

32、pandas.DataFrame.to_feather函数

32-1、语法

32-2、参数

32-3、功能

32-4、返回值

32-5、说明

32-6、用法

32-6-1、数据准备

32-6-2、代码示例

32-6-3、结果输出 

33、pandas.read_parquet函数

33-1、语法

33-2、参数

33-3、功能

33-4、返回值

33-5、说明

33-6、用法

33-6-1、数据准备

33-6-2、代码示例

33-6-3、结果输出 

二、推荐阅读

1、Python筑基之旅

2、Python函数之旅

3、Python算法之旅

4、Python魔法之旅

5、博客个人主页

一、用法精讲

31、pandas.read_feather函数
31-1、语法
# 31、pandas.read_feather函数
pandas.read_feather(path, columns=None, use_threads=True, storage_options=None, dtype_backend=_NoDefault.no_default)
Load a feather-format object from the file path.Parameters:
pathstr, path object, or file-like object
String, path object (implementing os.PathLike[str]), or file-like object implementing a binary read() function. 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.feather.columnssequence, default None
If not provided, all columns are read.use_threadsbool, default True
Whether to parallelize reading using multiple threads.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:
type of object stored in file
31-2、参数

31-2-1、path(必须)文件路径(字符串或路径对象),指向要读取的Feather格式文件。

31-2-2、columns(可选,默认值为None)指定要读取的列名列表,如果为None(默认值),则读取文件中的所有列,这可以用于减少内存使用,特别是当只需要文件中的部分列时。

31-2-3、use_threads(可选,默认值为True)是否使用多线程来加速读取过程,默认为True,意味着将尝试使用多线程来加速读取,但这可能取决于底层系统和Python解释器的实现,在某些情况下,关闭多线程(use_threads=False)可能会提供更好的性能。

31-2-4、storage_options(可选,默认值为None)用于文件系统的额外选项,比如S3或Google Cloud Storage等,这些选项将传递给底层的文件系统对象。对于大多数用户来说,这个参数可能不需要设置,除非你在处理存储在特殊存储系统中的Feather文件。

31-2-5、dtype_backend(可选)内部调用,通常不需要用户直接设置。

31-3、功能

        用于从文件路径中加载Feather格式的对象。

31-4、返回值

        返回值是存储在Feather文件中的对象类型,通常是pandas.DataFrame。如果Feather文件中存储的是DataFrame类型的数据,那么read_feather函数就会读取这些数据并返回一个DataFrame对象。

31-5、说明

        Feather格式是一种二进制文件格式,专为pandas DataFrame的高效读写而设计,它相比其他文本格式(如CSV)具有更快的读写速度和更小的文件大小,因此,这个函数非常适合于需要快速加载大型数据集的场景。

31-6、用法
31-6-1、数据准备
31-6-2、代码示例
# 31、pandas.read_feather函数
# 运行此程序,务必确保你已经安装了pyarrow或fastparquet库
import pandas as pd
import numpy as np
# 创建一个简单的DataFrame
df = pd.DataFrame({'A': np.random.randn(100),  # 生成100个正态分布的随机数'B': np.random.randint(1, 100, 100)  # 生成100个1到99之间的随机整数
})
# 保存到Feather文件
file_path = 'example.feather'
try:df.to_feather(file_path)print(f"DataFrame 已成功保存到 {file_path}")
except Exception as e:print(f"保存 Feather 文件时发生错误: {e}")
# 读取Feather文件
try:df_read = pd.read_feather(file_path)print("读取 Feather 文件成功!")# 显示读取的数据print(df_read.head())  # 只显示前几行,以避免打印太多数据
except FileNotFoundError:print(f"文件 {file_path} 未找到,请确保文件存在!")
except Exception as e:print(f"读取 Feather 文件时发生错误: {e}")
31-6-3、结果输出
# 31、pandas.read_feather函数
# DataFrame 已成功保存到 example.feather
# 读取 Feather 文件成功!
#           A   B
# 0 -0.425313  48
# 1 -1.915324  72
# 2 -0.391787  97
# 3 -0.014345  48
# 4  1.813109  53
32、pandas.DataFrame.to_feather函数
32-1、语法
# 32、pandas.DataFrame.to_feather函数
DataFrame.to_feather(path, **kwargs)
Write a DataFrame to the binary Feather format.Parameters:
path
str, path object, file-like object
String, path object (implementing os.PathLike[str]), or file-like object implementing a binary write() function. If a string or a path, it will be used as Root Directory path when writing a partitioned dataset.**kwargs
Additional keywords passed to pyarrow.feather.write_feather(). This includes the compression, compression_level, chunksize and version keywords.NotesThis function writes the dataframe as a feather file. Requires a default index. For saving the DataFrame with your custom index use a method that supports custom indices e.g. to_parquet.
32-2、参数

32-2-1、path(必须)文件路径(字符串或路径对象),指定输出文件的路径,可以是相对路径或绝对路径,如果文件已经存在,它会被覆盖。

32-2-2、**kwargs(可选)传递给PyArrow Feather写入器的额外关键字参数。虽然Pandas的文档可能不直接列出所有可能的参数,但PyArrow的Feather写入器支持一些有用的选项,例如压缩和元数据。以下是一些可能的有用参数(请注意,这些参数的可用性和具体行为可能随 PyArrow 的版本而异):

32-2-2-1、compression(可选,默认值为None)指定用于压缩文件的压缩算法,可选值包括'lz4', 'zstd', 'uncompressed'和'snappy'(注意:并非所有算法在所有平台上都可用)。

32-2-2-2、compression_level:int(对于某些压缩算法),指定压缩级别,较高的值通常会导致更好的压缩比,但也会增加压缩和解压缩的计算成本。

32-2-2-3、version:int(默认是最新支持的版本),指定要写入的Feather文件的版本,这通常不需要手动指定,除非你有特定的兼容性要求。

32-2-2-4、metadata(可选)一个字典,允许你为文件附加自定义元数据,这些数据将作为文件的元数据存储,可以在读取文件时检索。

32-3、功能

        用于将DataFrame保存为Feather格式的文件。

32-4、返回值

        本身不返回任何值(即返回None),它的主要作用是将DataFrame保存到指定的文件路径中,而不是生成一个新的DataFrame或其他对象。

32-5、说明

        无      

32-6、用法
32-6-1、数据准备
32-6-2、代码示例
# 32、pandas.DataFrame.to_feather函数
# 运行此程序,务必确保你已经安装了pyarrow或fastparquet库
import pandas as pd
# 创建一个示例 DataFrame
df = pd.DataFrame({'A': [1, 2, 3],'B': ['a', 'b', 'c']
})
# 将DataFrame保存为Feather文件
df.to_feather('example.feather')
# 注意:这里不会显示任何返回值,因为 to_feather() 不返回任何内容
# 但是,你可以通过检查文件系统来验证文件是否已被创建
# 稍后,你可以使用pd.read_feather()来重新加载数据
df_loaded = pd.read_feather('example.feather')
print(df_loaded)
32-6-3、结果输出 
# 32、pandas.DataFrame.to_feather函数
#    A  B
# 0  1  a
# 1  2  b
# 2  3  c
33、pandas.read_parquet函数
33-1、语法
# 33、pandas.read_parquet函数
pandas.read_parquet(path, engine='auto', columns=None, storage_options=None, use_nullable_dtypes=_NoDefault.no_default, dtype_backend=_NoDefault.no_default, filesystem=None, filters=None, **kwargs)
Load a parquet object from the file path, returning a DataFrame.Parameters:
pathstr, path object or file-like object
String, path object (implementing os.PathLike[str]), or file-like object implementing a binary read() function. The string could be a URL. Valid URL schemes include http, ftp, s3, gs, and file. For file URLs, a host is expected. A local file could be: file://localhost/path/to/table.parquet. A file URL can also be a path to a directory that contains multiple partitioned parquet files. Both pyarrow and fastparquet support paths to directories as well as file URLs. A directory path could be: file://localhost/path/to/tables or s3://bucket/partition_dir.engine{‘auto’, ‘pyarrow’, ‘fastparquet’}, default ‘auto’
Parquet library to use. If ‘auto’, then the option io.parquet.engine is used. The default io.parquet.engine behavior is to try ‘pyarrow’, falling back to ‘fastparquet’ if ‘pyarrow’ is unavailable.When using the 'pyarrow' engine and no storage options are provided and a filesystem is implemented by both pyarrow.fs and fsspec (e.g. “s3://”), then the pyarrow.fs filesystem is attempted first. Use the filesystem keyword with an instantiated fsspec filesystem if you wish to use its implementation.columnslist, default=None
If not None, only these columns will be read from the file.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.New in version 1.3.0.use_nullable_dtypesbool, default False
If True, use dtypes that use pd.NA as missing value indicator for the resulting DataFrame. (only applicable for the pyarrow engine) As new dtypes are added that support pd.NA in the future, the output with this option will change to use those dtypes. Note: this is an experimental option, and behaviour (e.g. additional support dtypes) may change without notice.Deprecated since version 2.0.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.filesystemfsspec or pyarrow filesystem, default None
Filesystem object to use when reading the parquet file. Only implemented for engine="pyarrow".New in version 2.1.0.filtersList[Tuple] or List[List[Tuple]], default None
To filter out data. Filter syntax: [[(column, op, val), …],…] where op is [==, =, >, >=, <, <=, !=, in, not in] The innermost tuples are transposed into a set of filters applied through an AND operation. The outer list combines these sets of filters through an OR operation. A single list of tuples can also be used, meaning that no OR operation between set of filters is to be conducted.Using this argument will NOT result in row-wise filtering of the final partitions unless engine="pyarrow" is also specified. For other engines, filtering is only performed at the partition level, that is, to prevent the loading of some row-groups and/or files.New in version 2.1.0.**kwargs
Any additional kwargs are passed to the engine.Returns:
DataFrame
33-2、参数

33-2-1、path(必须)Parquet文件的路径,可以是相对路径或绝对路径。

33-2-2、engine(可选,默认值为'auto')指定用于读取Parquet文件的底层库,'auto'会自动选择(通常基于已安装的库),'pyarrow'和'fastparquet'是两个流行的Parquet库。

33-2-3、columns(可选,默认值为None)要读取的列名列表,如果指定,则只读取这些列,这可以显著减少内存使用和数据加载时间。

33-2-4、storage_options(可选,默认值为None)传递给文件系统的额外选项,如认证信息或配置设置,这通常用于处理存储在云存储(如AWS S3、Google Cloud Storage)上的Parquet文件。

33-2-5、use_nullable_dtypes(可选)如果为True,则使用Pandas的可空数据类型(如pd.Int64Dtype()、pd.StringDtype())来读取数据,这可以提高数据的准确性和性能,尤其是在处理大型数据集时;如果未指定,则根据Pandas的版本和配置自动选择。

33-2-6、dtype_backend(可选)内部调用,通常不需要用户手动设置。

33-2-7、filesystem(可选,默认值为None)用于读取Parquet文件的文件系统实例,这通常与storage_options一起使用,以处理存储在特定存储系统上的文件。

33-2-8、filters(可选,默认值为None)用于在读取Parquet文件时应用过滤器的表达式列表,这可以显著减少需要加载到内存中的数据量,过滤器的具体语法取决于底层Parquet引擎。

33-2-9、**kwargs(可选)其他关键字参数将传递给底层的Parquet读取器,这些参数可能因使用的引擎而异,因此请参考相应引擎的文档以获取更多信息。

33-3、功能

        从指定的文件路径加载Parquet格式的数据,并返回一个Pandas DataFrame对象。

33-4、返回值

        返回一个Pandas DataFrame对象,该对象包含了从Parquet文件中读取的数据。

33-5、说明

33-5-1、在处理大型Parquet文件时,建议合理使用columns和filters参数,以减少加载到内存中的数据量,提高读取效率。

33-5-2、如果Parquet文件存储在云存储上,需要确保已经正确设置了storage_options和(如果需要)filesystem参数,以便能够成功访问和读取文件。

33-5-3、use_nullable_dtypes和dtype_backend参数提供了对数据类型处理的精细控制,但通常不需要手动设置,除非在特定情况下需要优化性能或兼容性。

33-5-4、Parquet是一种列式存储的文件格式,非常适合于大数据的存储和高效读写,通过这个函数,用户可以轻松地将存储在Parquet文件中的数据加载到Pandas DataFrame中,以便进行进一步的数据分析或处理。

33-6、用法
33-6-1、数据准备
33-6-2、代码示例
# 33、pandas.read_parquet函数
# 运行此程序,务必确保你已经安装了pyarrow或fastparquet库
import pandas as pd
# 创建一个Pandas DataFrame
data = {'id': [1, 2, 3, 4],'name': ['Alice', 'Bob', 'Charlie', 'David'],'age': [25, 30, 35, 40],'city': ['New York', 'Los Angeles', 'Chicago', 'Houston']
}
df = pd.DataFrame(data)
# 指定Parquet文件的保存路径
parquet_path = 'example.parquet'
# 将DataFrame保存为Parquet文件
df.to_parquet(parquet_path, engine='pyarrow', compression='snappy')
print(f"Parquet文件已成功保存到:{parquet_path}")
# 读取Parquet文件
df_read = pd.read_parquet(parquet_path, engine='pyarrow')
# 显示读取的DataFrame以验证数据
print("读取的Parquet文件内容:")
print(df_read)
33-6-3、结果输出 
# 33、pandas.read_parquet函数
# Parquet文件已成功保存到:example.parquet
# 读取的Parquet文件内容:
#    id     name  age         city
# 0   1    Alice   25     New York
# 1   2      Bob   30  Los Angeles
# 2   3  Charlie   35      Chicago
# 3   4    David   40      Houston

二、推荐阅读

1、Python筑基之旅
2、Python函数之旅
3、Python算法之旅
4、Python魔法之旅
5、博客个人主页

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://xiahunao.cn/news/3225858.html

如若内容造成侵权/违法违规/事实不符,请联系瞎胡闹网进行投诉反馈,一经查实,立即删除!

相关文章

小白学c嘎嘎(第二天)入门基础下

温馨提醒&#xff1a;本篇文章起&#xff0c;文章内容排版将更新&#xff0c;层层深入 基础知识 回顾 引用的语法格式&#xff1a;类型& 引⽤别名 引⽤对象; 引用特性 1. 引⽤在定义时必须初始化 2. ⼀个变量可以有多个引⽤ 3. ⼀旦引⽤⼀个实体&#xff0c;再不…

android Dialog全屏沉浸式状态栏实现

在Android中&#xff0c;创建沉浸式状态栏通常意味着让状态栏背景与应用的主题颜色一致&#xff0c;并且让对话框在状态栏下面显示&#xff0c;而不是浮动。为了实现这一点&#xff0c;你可以使用以下代码片段&#xff1a; 1、实际效果图&#xff1a; 2、代码实现&#xff1a;…

【解读大模型(LLM)的token】

文末有福利&#xff01; 当人们谈论大型语言模型的大小时&#xff0c;参数会让我们了解神经网络的结构有多复杂&#xff0c;而token的大小会让我们知道有多少数据用于训练参数。 正像陆奇博士所说的那样&#xff0c;大型语言模型为从文本生成到问题回答的各种任务提供了令人印象…

11410-00SF 同轴连接器

型号简介 11410-00SF是Southwest Microwave的连接器。该连接器的外壳采用优质不锈钢&#xff0c;材质为 CRES ALLOY UNS-S303500&#xff0c;符合 ASTM-A582 标准。首先&#xff0c;不锈钢材料经过锻造加工&#xff0c;形成转接器的基本形状。然后&#xff0c;外壳进行精密的 C…

雷池WAF动态防护功能初体验

一、 介绍 大名鼎鼎的雷池WAF最近新上了个名为 动态防护 的功能 所谓动态防护&#xff0c;是在用户浏览到的网页内容不变的情况下&#xff0c;将网页赋予动态特性&#xff0c;即使是静态页面&#xff0c;也会具有动态的随机性。 说白了就是给你网站的 html 和 js 代码加上加密…

WEB安全:网络安全常用术语

一、攻击类别 漏洞&#xff1a;硬件、软件、协议&#xff0c;代码层次的缺陷。 后⻔&#xff1a;方便后续进行系统留下的隐蔽后⻔程序。 病毒&#xff1a;一种可以自我复制并传播&#xff0c;感染计算机和网络系统的恶意软件(Malware)&#xff0c;它能损害数据、系统功能或拦…

浅谈“不要卷模型,要卷应用”

目录 1.概述 2.AI技术应用场景探索 3.避免超级应用陷阱的策略 3.1.追求DAU的弊端 3.2.平衡用户活跃度与应用实用性的策略 4.个性化智能体开发 4.1. 用户需求分析与数据收集 4.2. 技术选择与开发 4.3. 个性化算法设计 4.4. 安全性与隐私保护 4.5. 多渠道集成与响应机…

防火墙安全策略用户认证综合实验

目录 一、拓扑图 二、实验要求 三、实验步骤 步骤1&#xff1a;配置防火墙接口 步骤2&#xff1a;配置ISP 步骤3&#xff1a;配置交换机LSW1 步骤4&#xff1a;配置PC端、客户端、服务器端 需求1&#xff1a;针对访问DMZ区内的服务器 ​编辑测试需求1: 需求2&#xff…

transformer维度变化,图中直观表现

transformer维度变化&#xff0c;图中直观表现 Transformer分为两阶段&#xff1a;训练&#xff0c;推理&#xff1a;训练阶段&#xff1a;Encoder部分&#xff1a;Decoder部分&#xff1a; 推理阶段&#xff1a;训练阶段图片推理阶段图片 Transformer分为两阶段&#xff1a;训…

WPF界面设计-更改按钮样式 自定义字体图标

一、下载图标文件 iconfont-阿里巴巴矢量图标库 二、xaml界面代码编辑 文件结构 &#xe653; 对应的图标代码 Fonts/#iconfont 对应文件位置 <Window.Resources><ControlTemplate TargetType"Button" x:Key"CloseButtonTemplate"…

Web3D技术应用在什么场景,能给企业带来什么价值?

Web3D现在已经在很多行业和领域应用了&#xff0c;以 博维数孪 行业用户为例&#xff0c;它能够为企业带来一系列价值&#xff1a; 1、电商领域&#xff1a;在电商中&#xff0c;Web3D技术可以提供3D商品展示&#xff0c;让消费者能够全面了解商品的每一个细节&#xff0c;并且…

【高中数学/幂函数】比较a=2^0.3,b=3^0.2,c=7^0.1的大小

【问题】 比较a2^0.3,b3^0.2,c7^0.1的大小 【解答】 a2^0.32^3/10(2^3)^1/108^1/10 b3^0.23^2/10(3^2)^1/109^1/10 c7^0.17^1/10 由于yx^1/10在x正半轴是增函数&#xff0c;底数大的得数就大。 因为9>8>7,所以b>a>c 【图像】 在图像上绘出曲线yx^1/10&…

从数据仓库到数据湖(上):数据湖导论

文章目录 一、什么是数据湖&#xff1f;起源数据湖的特征 二、为什么要用数据湖&#xff1f;三、数据湖与数据仓库的区别数据仓库和数据湖的对比 四、数据湖本质数据存储架构数据处理工具&#xff1a;三类第一类工具第二类工具第三类工具 小结 五、总结六、参考资料 一、什么是…

K8s GPU 资源管理探索:在 KubeSphere 上部署 AI 大模型 Ollama

作者&#xff1a;运维有术星主 随着人工智能、机器学习、AI 大模型技术的迅猛发展&#xff0c;我们对计算资源的需求也在不断攀升。特别是对于需要处理大规模数据和复杂算法的 AI 大模型&#xff0c;GPU 资源的使用变得至关重要。对于运维工程师而言&#xff0c;掌握如何在 Kub…

发送手机,邮箱验证码

一、发送邮箱&#xff0c;使用hutool工具包 使用aliyun邮箱作为发件邮箱&#xff0c;需要在邮箱中开启代收功能 1、引入依赖 userController代码 GetMapping("/sendCodeEmail")public Integer sendCodeEmail(String mel){return userService.sendCodeEmail(mel);} …

!vue3中defineEmits接收父组件向子组件传递方法,以及方法所需传的参数及类型定义,避免踩坑!

使用说明 1、在子组件中调用defineEmits并定义要发射给父组件的方法 const emits defineEmits([‘foldchange’]) 2、使用defineEmits会返回一个方法&#xff0c;使用一个变量emits(变量名随意)去接收 3、在子组件要触发的方法中&#xff0c;调用emits并传入发射给父组件的方法…

绝地归来!英伟达等提出JeDi:无需微调,个性化图像生成新SOTA![CVPR 2024]

文章链接&#xff1a;https://arxiv.org/pdf/2407.06187 github链接&#xff1a;https://research.nvidia.com/labs/dir/jedi 本文提出了一种无需微调的文本生成图像方法&#xff0c;采用了新颖的联合图像扩散模型。 提出了一种简单且可扩展的数据合成流程&#xff0c;用于生成…

Quartz 核心

一、Quartz 核心 工作原理&#xff1a; Scheduler 是一个计划调度器容器&#xff08;总部&#xff09;&#xff0c;容器里面可以盛放众多的 JobDetail 和 Trigger。当容器启动后&#xff0c;里面的每个 JobDetail 都会根据 Trigger 按部就班自动去执行。JobDetail 是一个可执…

Canvas:掌握图像变换合成与裁剪状态像素操作

想象一下&#xff0c;用几行代码就能创造出如此逼真的图像和动画&#xff0c;仿佛将艺术与科技完美融合&#xff0c;前端开发的Canvas技术正是这个数字化时代中最具魔力的一环&#xff0c;它不仅仅是网页的一部分&#xff0c;更是一个无限创意的画布&#xff0c;一个让你的想象…

软件源码购买一般在哪个网站?避坑指南

在数字化转型的浪潮中&#xff0c;软件源码的购买已成为许多企业和个人开发者快速搭建项目、节省开发成本的重要途径。选择合适的购买平台&#xff0c;不仅能确保源码的质量与合法性&#xff0c;还能享受到便捷的交易流程与专业的售后服务。本文小编将为您分享几个常见的软件源…