人生苦短我用Python pandas文件格式转换

人生苦短我用Python pandas文件格式转换

  • 前言
  • 示例1 excel与csv互转
  • 常用格式的方法
    • Flat file
    • Excel
    • JSON
    • XML
  • 示例2 常用格式转换
    • 简要需求
    • 依赖
    • export方法
    • main方法
  • 附其它格式的方法
    • HTML
    • Pickling
    • Clipboard
    • Latex
    • HDFStore: PyTables (HDF5)
    • Feather
    • Parquet
    • ORC
    • SAS
    • SPSS
    • SQL
    • Google BigQuery
    • STATA

前言

pandas支持多种文件格式,通过pandasIO方法,可以实现不同格式之间的互相转换。本文通过excelcsv互转的示例和pandas的支持的文件格式,实现一个简单的文件格式转换的功能。

示例1 excel与csv互转

在前文实现了excel转csv,即通过pandasexcelcsv,反过来也可以将csv转为excel

下面是excelcsv互转的示例代码:

  • excel转csv
def export_csv(input_file, output_path):# 创建ExcelFile对象with pd.ExcelFile(input_file) as xls:# 获取工作表名称列表for i, sheet_name in enumerate(xls.sheet_names):# 读取工作表并转换为DataFramedf = pd.read_excel(xls, sheet_name=sheet_name)output_file = os.path.join(output_path, f'{i + 1}-{sheet_name}.csv')# 将DataFrame中的数据写入CSV文件。df.to_csv(output_file, index=False)
  • csv转为excel
def export_excel(input_file, output_file):if not output_file:input_path = pathlib.Path(input_file)output_path = input_path.parent / (input_path.stem + '.xlsx')output_file = str(output_path)df = pd.read_csv(input_file)df.to_excel(output_file, index=False)

常用格式的方法

以下来自pandas官网 Input/Outout部分

Flat file

方法说明
read_table(filepath_or_buffer, *[, sep, …])Read general delimited file into DataFrame.
read_csv(filepath_or_buffer, *[, sep, …])Read a comma-separated values (csv) file into DataFrame.
DataFrame.to_csv([path_or_buf, sep, na_rep, …])Write object to a comma-separated values (csv) file.
read_fwf(filepath_or_buffer, *[, colspecs, …])Read a table of fixed-width formatted lines into DataFrame.

Excel

方法说明
read_excel(io[, sheet_name, header, names, …])Read an Excel file into a pandas DataFrame.
DataFrame.to_excel(excel_writer, *[, …])Write object to an Excel sheet.
ExcelFile(path_or_buffer[, engine, …])Class for parsing tabular Excel sheets into DataFrame objects.
ExcelFile.book
ExcelFile.sheet_names
ExcelFile.parse([sheet_name, header, names, …])Parse specified sheet(s) into a DataFrame.
方法说明
Styler.to_excel(excel_writer[, sheet_name, …])Write Styler to an Excel sheet.
方法说明
ExcelWriter(path[, engine, date_format, …])Class for writing DataFrame objects into excel sheets.

JSON

方法说明
read_json(path_or_buf, *[, orient, typ, …])Convert a JSON string to pandas object.
json_normalize(data[, record_path, meta, …])Normalize semi-structured JSON data into a flat table.
DataFrame.to_json([path_or_buf, orient, …])Convert the object to a JSON string.
方法说明
build_table_schema(data[, index, …])Create a Table schema from data.

XML

方法说明
read_xml(path_or_buffer, *[, xpath, …])Read XML document into a DataFrame object.
DataFrame.to_xml([path_or_buffer, index, …])Render a DataFrame to an XML document.

示例2 常用格式转换

根据常用格式的IO方法,完成一个常用格式的格式转换功能。

第一步从指定格式的文件中读取数据,并将其转换为 DataFrame 对象。

第二部将 DataFrame 中的数据写入指定格式的文件中。

简要需求

  • 根据输入输出的文件后缀名,自动进行格式转换,若格式不支持输出提示。
  • 支持的格式csvxlsxjsonxml

依赖

pip install pandas
pip install openpyxl
pip install lxml

export方法

def export(input_file, output_file):if not os.path.isfile(input_file):print('Input file does not exist')returnif input_file.endswith('.csv'):df = pd.read_csv(input_file, encoding='utf-8')elif input_file.endswith('.json'):df = pd.read_json(input_file, encoding='utf-8')elif input_file.endswith('.xlsx'):df = pd.read_excel(input_file)elif input_file.endswith('.xml', encoding='utf-8'):df = pd.read_xml(input_file)else:print('Input file type not supported')returnif output_file.endswith('.csv'):df.to_csv(output_file, index=False)elif output_file.endswith('.json'):df.to_json(output_file, orient='records', force_ascii=False)elif output_file.endswith('.xlsx'):df.to_excel(output_file, index=False)elif output_file.endswith('.xml'):df.to_xml(output_file, index=False)elif output_file.endswith('.html'):df.to_html(output_file, index=False, encoding='utf-8')else:print('Output file type not supported')return

main方法

def main(argv):input_path = Noneoutput_path = Nonetry:shortopts = "hi:o:"longopts = ["ipath=", "opath="]opts, args = getopt.getopt(argv, shortopts, longopts)except getopt.GetoptError:print('usage: export.py -i <inputpath> -o <outputpath>')sys.exit(2)for opt, arg in opts:if opt in ("-h", "--help"):print('usage: export.py -i <inputpath> -o <outputpath>')sys.exit()elif opt in ("-i", "--ipath"):input_path = argelif opt in ("-o", "--opath"):output_path = argprint(f'输入路径为:{input_path}')print(f'输出路径为:{output_path}')export(input_path, output_path)

附其它格式的方法

以下来自pandas官网 Input/Outout部分

HTML

方法说明
read_html(io, *[, match, flavor, header, …])Read HTML tables into a list of DataFrame objects.
DataFrame.to_html([buf, columns, col_space, …])Render a DataFrame as an HTML table.
方法说明
Styler.to_html([buf, table_uuid, …])Write Styler to a file, buffer or string in HTML-CSS format.

Pickling

方法说明
read_pickle(filepath_or_buffer[, …])Load pickled pandas object (or any object) from file.
DataFrame.to_pickle(path, *[, compression, …])Pickle (serialize) object to file.

Clipboard

方法说明
read_clipboard([sep, dtype_backend])Read text from clipboard and pass to read_csv().
DataFrame.to_clipboard(*[, excel, sep])Copy object to the system clipboard.

Latex

方法说明
DataFrame.to_latex([buf, columns, header, …])Render object to a LaTeX tabular, longtable, or nested table.
方法说明
Styler.to_latex([buf, column_format, …])Write Styler to a file, buffer or string in LaTeX format.

HDFStore: PyTables (HDF5)

方法说明
read_hdf(path_or_buf[, key, mode, errors, …])Read from the store, close it if we opened it.
HDFStore.put(key, value[, format, index, …])Store object in HDFStore.
HDFStore.append(key, value[, format, axes, …])Append to Table in file.
HDFStore.get(key)Retrieve pandas object stored in file.
HDFStore.select(key[, where, start, stop, …])Retrieve pandas object stored in file, optionally based on where criteria.
HDFStore.info()Print detailed information on the store.
HDFStore.keys([include])Return a list of keys corresponding to objects stored in HDFStore.
HDFStore.groups()Return a list of all the top-level nodes.
HDFStore.walk([where])Walk the pytables group hierarchy for pandas objects.

Warning

One can store a subclass of DataFrame or Series to HDF5, but the type of the subclass is lost upon storing.

Feather

方法说明
read_feather(path[, columns, use_threads, …])Load a feather-format object from the file path.
DataFrame.to_feather(path, **kwargs)Write a DataFrame to the binary Feather format.

Parquet

方法说明
read_parquet(path[, engine, columns, …])Load a parquet object from the file path, returning a DataFrame.
DataFrame.to_parquet([path, engine, …])Write a DataFrame to the binary parquet format.

ORC

方法说明
read_orc(path[, columns, dtype_backend, …])Load an ORC object from the file path, returning a DataFrame.
DataFrame.to_orc([path, engine, index, …])Write a DataFrame to the ORC format.

SAS

方法说明
read_sas(filepath_or_buffer, *[, format, …])Read SAS files stored as either XPORT or SAS7BDAT format files.

SPSS

方法说明
read_spss(path[, usecols, …])Load an SPSS file from the file path, returning a DataFrame.

SQL

方法说明
read_sql_table(table_name, con[, schema, …])Read SQL database table into a DataFrame.
read_sql_query(sql, con[, index_col, …])Read SQL query into a DataFrame.
read_sql(sql, con[, index_col, …])Read SQL query or database table into a DataFrame.
DataFrame.to_sql(name, con, *[, schema, …])Write records stored in a DataFrame to a SQL database.

Google BigQuery

方法说明
read_gbq(query[, project_id, index_col, …])(DEPRECATED) Load data from Google BigQuery.

STATA

方法说明
read_stata(filepath_or_buffer, *[, …])Read Stata file into DataFrame.
DataFrame.to_stata(path, *[, convert_dates, …])Export DataFrame object to Stata dta format.
方法说明
StataReader.data_labelReturn data label of Stata file.
StataReader.value_labels()Return a nested dict associating each variable name to its value and label.
StataReader.variable_labels()Return a dict associating each variable name with corresponding label.
StataWriter.write_file()Export DataFrame object to Stata dta format.

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

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

香橙派转换模型以及在开发板上部署

新手小白记录一下自己使用香橙派模型转换以及在开发板上运行的过程&#xff0c;防止后面忘记。 使用的开发板&#xff1a;Orange Pi 5 Plus&#xff08;rk3588&#xff09; 官方的一些资料在&#xff08;主要参考用户手册&#xff09;&#xff1a;Orange Pi - Orangepihttp:/…

Pytest夹具autouse参数使用。True表示会自动在测试中使用,而无需显式指定

1. 全局conftest文件日志记录功能 # 当前路径(使用 abspath 方法可通过dos窗口执行) current_path os.path.dirname(os.path.abspath(__file__)) # 上上级目录 ffather_path os.path.abspath(os.path.join(current_path,"../"))LOG_FILE_PATH f{ffather_path}/lo…

【视频讲解】Python贝叶斯卷积神经网络分类胸部X光图像数据集实例

全文链接&#xff1a;https://tecdat.cn/?p37604 分析师&#xff1a;Yuanchun Niu 在人工智能的诸多领域中&#xff0c;分类技术扮演着核心角色&#xff0c;其应用广泛而深远。无论是在金融风险评估、医疗诊断、安全监控还是日常的交互式服务中&#xff0c;有效的分类算法都是…

科研绘图系列:R语言富集散点图(enrichment scatter plot)

介绍 富集通路散点图(Enrichment Pathway Scatter Plot)是一种数据可视化工具,用于展示基因集富集分析(Gene Set Enrichment Analysis, GSEA)的结果。 横坐标是对应基因名称,纵坐标是通路名称,图中的点表示该基因在某个通路下的qvalue,可以简单理解为不同环境下的贡献…

【全网最全】2024年数学建模国赛A题30页完整建模文档+17页成品论文+保奖matla代码+可视化图表等(后续会更新)

您的点赞收藏是我继续更新的最大动力&#xff01; 一定要点击如下的卡片那是获取资料的入口&#xff01; 【全网最全】2024年数学建模国赛A题30页完整建模文档17页成品论文保奖matla代码可视化图表等&#xff08;后续会更新&#xff09;「首先来看看目前已有的资料&#xff0…

【ACM独立出版|EI快检索-高录用|IEEE Fellow支持】2024年数字经济与计算机科学国际学术会议(DECS2024)

【ACM独立出版&#xff5c;EI快检索-高录用&#xff5c;IEEE Fellow支持】 2024年数字经济与计算机科学国际学术会议&#xff08;DECS2024&#xff09; *ACM独立出版&#xff0c;快检索&#xff0c;高录用 *见刊后1个月左右完成EI&Scopus检索 *国内211大学、世界QS名校…

系统架构师-ERP+集成

ERP 集成平台end&#xff1a;就懒得画新的页

MyBatis-MappedStatement什么时候生成?QueryWrapper如何做到动态生成了SQL?

通过XML配置的MappedStatement 这部分MappedStatement主要是由MybatisXMLMapperBuilder进行解析&#xff0c;核心逻辑如下&#xff1a; 通过注解配置的MappedStatement 核心逻辑就在这个里面了&#xff1a; 继承BaseMapper的MappedStatement 我们看看这个类&#xff0c;里…

python strip()函数使用

默认情况下去除字符串首尾的空格和换行符号&#xff1b; 但是也可以去掉任意的字符串&#xff0c;可以把首尾的字符串去除到再也找不到为止&#xff0c;但是需要注意可能会由于空格和换行符的存在使得待去除的字符串没有被去除&#xff1a; a "[[1,2,3,4,5], [2,3,4,5]]…

Java项目——苍穹外卖(一)

Entity、DTO、VO Entity&#xff08;实体&#xff09; Entity 是表示数据库表的对象&#xff0c;通常对应数据库中的一行数据。它通常包含与数据库表对应的字段&#xff0c;并可能包含一些业务逻辑。 DTO&#xff08;数据传输对象&#xff09; 作用&#xff1a;DTO 是用于在…

【小沐学OpenGL】Ubuntu环境下glfw的安装和使用

文章目录 1、简介1.1 OpenGL简介1.2 glfw简介 2、安装glfw2.1 直接命令二进制安装2.2 源码安装 3、测试glfw3.1 测试1&#xff0c;glfwglew3.2 测试2&#xff0c;glfwglad3.3 测试3 结语 1、简介 1.1 OpenGL简介 OpenGL作为图形界的工业标准&#xff0c;其仅仅定义了一组2D和…

美团面试题:生成字符串的不同方式

美团面试题:生成字符串的不同方式 引言问题分析动态规划思路伪代码C代码实现代码解析复杂度分析优化建议结论引言 小红拿到了一个空字符串 s s s,她希望通过两种操作生成一个给定的字符串 t t t。我们需要计算生成字符串

python(进阶2)实现自动化注册和登录

1. 分析需求 后端完成接口以后&#xff0c;工作中可能会涉及到自测通断&#xff0c;a接口和b接口之间可能有关联关系&#xff0c;例如:a接口注册&#xff0c;b接口登录&#xff0c;就需要a接口返回的参数传递到b接口 2. 环境准备 需要这些类包 import requests import rand…

Vivado编译报错黑盒子问题

1 问题描述 “Black Box Instances: Cell **** of type ** has undefined contents and is considered a back box. The contents of this cell must be defined for opt_design to complete successfully.” 检查工程代码提示的模块&#xff0c;该模块为纯手写的Veril…

替代 Django 默认 User 模型并使用 `django-mysql` 添加数据库备注20240904

替代 Django 默认 User 模型并使用 django-mysql 添加数据库备注 前言 在 Django 项目开发中&#xff0c;默认的 User 模型虽然能够满足许多基础需求&#xff0c;但在实际项目中我们常常需要对用户模型进行定制化。通过覆盖默认的 User 模型&#xff0c;我们可以根据具体的业…

注册安全分析报告:熊猫频道

前言 由于网站注册入口容易被黑客攻击&#xff0c;存在如下安全问题&#xff1a; 暴力破解密码&#xff0c;造成用户信息泄露短信盗刷的安全问题&#xff0c;影响业务及导致用户投诉带来经济损失&#xff0c;尤其是后付费客户&#xff0c;风险巨大&#xff0c;造成亏损无底洞…

【论文阅读】CiteTracker: Correlating Image and Text for Visual Tracking

paper&#xff1a;[2308.11322] CiteTracker: Correlating Image and Text for Visual Tracking (arxiv.org) code&#xff1a;NorahGreen/CiteTracker: [ICCV23] CiteTracker: Correlating Image and Text for Visual Tracking (github.com) 简介 现有的视觉跟踪方法通常以…

iOS——frame和bounds的区别

把frame理解为占用区域&#xff0c;把bounds理解为边界。View在旋转过程中&#xff0c;其实自己的坐标系统并没有发生改变&#xff0c;bounds中的origin只能通过setBounds方法修改。 frame 定义了视图在其父视图坐标系统中的位置和大小。其坐标系是相对于俯视图的坐标系。 bou…

如何保证 UDP 的可靠性传输?

一、TCP 和 UDP 的区别 1、TCP基于连接&#xff0c;UDP基于无连接。 2、对系统资源的要求&#xff1a;TCP 较多&#xff0c;UDP 少。 3、UDP 程序结构较简单。 4、TCP基于流模式&#xff0c;UDP基于数据报模式 。 5、TCP 保证数据正确性&#xff0c;UDP 不保证数据准确性&…

滚雪球学MyBatis(03):基本配置

前言 欢迎回到我们的MyBatis系列教程。在上一期中&#xff0c;我们详细讲解了MyBatis的环境搭建&#xff0c;包括JDK、Maven/Gradle的安装和配置&#xff0c;以及MySQL数据库的准备工作。现在&#xff0c;我们已经搭建好了开发环境&#xff0c;是时候开始配置MyBatis了。本期内…