![](/img/trans.png)
[英]Python Pandas - When using read_excel or csv is it possible to convert data type by referencing the column number?
[英]Preserving the Custom Number Format when using read_excel() then converting to CSV with to_csv() with Pandas
我创建了一个使用 Pandas 将 Excel 文件转换为 CSV 的简单脚本。 这是我的代码的要点:
read_file = pd.read_excel(excel_file)
read_file.to_csv(csv_file, index=None, header=True, float_format='%.0f')
但是,我的问题是 Excel 文件有几列带有日期,而 CSV 文件中的输出是单元格的文字值,格式为 mm/dd/yyyy。 在 Excel 文件中,已应用自定义数字格式将日期转换为 mmm yyyy 格式(例如 01/01/2001 变为 Jan 2001)。
我想将 Excel 转换为 CSV 并将日期值保留在其自定义数字格式中,而不是单元格中的文字值。 这可能吗?
PS 我知道在to_csv()
中添加date_format
,但我更喜欢保留自定义数字格式,因为此工具将用于许多不同的 Excel 文件,这些文件可能包含也可能不包含自己的自定义数字格式。 这就是为什么我很难过。
使用数字格式呈现单元格值是 Excel 的一项功能。 我觉得pandas和openpyxl只知道表格的信息,比如数值和数字格式,却不知道如何按照数字格式渲染单元格值。
如果我们愿意,我们可以将值呈现为基于数字格式的字符串,就像 Excel 一样。 我们可以通过openpyxl获取单元格的数字格式。
import openpyxl
workbook = openpyxl.load_workbook(excel_file)
sheet = workbook[workbook.sheetnames[0]]
print(sheet.cell(2,1).number_format)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.