简体   繁体   English

如何在不修改第一行的情况下使用 Pandas 将 excel 文件转换为 csv 文件?

[英]How do I convert excel file into csv file using pandas without the first row being modified?

I am trying to convert multiples excel files into csv files.我正在尝试将多个 excel 文件转换为 csv 文件。 However, when using the codes below, I am having issues with pandas modifying the values in the first row.但是,当使用下面的代码时,我在修改第一行中的值时遇到了熊猫问题。

for i in path_list:
     df = pd.read_excel(i) 
     df.to_csv(i[:-5]+".csv", index = None, header=True)

Below is an example of how pandas modifies the first row values.下面是 pandas 如何修改第一行值的示例。

Excel:
1     1     1     2     2     2
21    32    3     54    6     86

CSV:
1    1.1    1.2    2    2.1    2.2
21   32     3      54   6      86

How can I fix this issue so that the values in the CSV file will be exactly the same as in the excel file.如何解决此问题,以便 CSV 文件中的值与 Excel 文件中的值完全相同。

Looks like your excel has duplicate column names.看起来你的excel有重复的列名。 So when you read excel into df , it appends .1, .2 after all duplicated column names.因此,当您将excel读入df ,它会在所有重复的列名之后附加.1, .2

You can do this to fix it:你可以这样做来修复它:

for i in path_list:
     df = pd.read_excel(i)
     df.columns = df.columns.astype(str).str.split('.').str[0] 
     df.to_csv(i[:-5]+".csv", index = None, header=True)

df.columns = df.columns.astype(str).str.split('.').str[0] command will remove .1, .2 from duplicate column names and will keep them the way they were in excel. df.columns = df.columns.astype(str).str.split('.').str[0]命令将从重复的列名中删除.1, .2并保持它们在 excel 中的方式。

The same will be written in your csv also.同样的内容也将写入您的csv

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在不使用 Pandas 的情况下在 Python 中逐行编辑 CSV 文件 - How to edit a CSV file row by row in Python without using Pandas 如何使用 Z3A43B4F88325D94022C0EFA 库在 python 的 2 列 CSV 文件上更改 header 而不创建新的 C9 文件? - How do I change the header on a 2 column CSV file in python using the pandas library without creating a new file? 如果文件的最后修改日期是今天,如何将Excel文件导入Pandas? - How do I import an Excel file to Pandas if the file's last modified date is today? 如何在不添加重复项的情况下使用 pandas 更新 CSV 文件 - How do I update a CSV file with pandas without adding duplicates 如何使用 Pandas 将 Excel 文件转换为嵌套的 JSON 文件? - How do I use Pandas to convert an Excel file to a nested JSON? 如何在不使用 Pandas 的情况下对 CSV 文件进行操作? - How to do operations of a CSV file without using Pandas? 如何使用 python 中的 pandas 转换 csv 文件中的列中的日期格式? - How do I convert date format in a column in a csv file using pandas in python? 我如何发送带有 python pandas 的 emsil csv 附件而不使用 to_csv 文件导出到 Z628CB5675FF524F3E719B7AA2E - how do i send emsil csv attachment with python pandas without exporting to csv file ithut using to_csv 如何使用python将.csv文件转换为.db文件? - How do I convert a .csv file to .db file using python? 使用Pandas如何对以块状态读取的文件进行重复数据删除? - Using Pandas how do I deduplicate a file being read in chunks?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM