Python 使用 pandas 将 xlsx 转换为 csv 文件。如何删除索引列?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42422509/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python using pandas to convert xlsx to csv file. How to delete index column?
提问by acb
I am using the following code to convert .xlsx files into .csv files.
我正在使用以下代码将 .xlsx 文件转换为 .csv 文件。
import pandas as pd
data_xls = pd.read_excel('excelfile.xlsx', 'Sheet2', index_col=None)
data_xls.to_csv('csvfile.csv', encoding='utf-8')
The code is working, however I am getting an index column with the cell numbers which I do not want. Is there anyway to not include or remove that index column?
代码正在运行,但是我得到了一个包含我不想要的单元格编号的索引列。无论如何不包括或删除该索引列?
File output
文件输出
Unnamed Data
0 0.99319613
1 0.99319613
2 0.99319613
3 0.99319613
4 0.99319613
5 0.99319613
回答by miradulo
As noted in the docs for DataFrame.to_csv()
, simply pass index=False
as a keyword argument to not write row names.
如 文档中所述DataFrame.to_csv()
,只需index=False
作为关键字参数传递即可不写入行名称。
data_xls.to_csv('csvfile.csv', encoding='utf-8', index=False)
回答by Kumar S
To remove Column names:
删除列名:
data_xls.to_csv("filename.csv",index=False,header=None ,encoding='utf-8')
data_xls.to_csv("filename.csv",index=False,header=None ,encoding='utf-8')
回答by Punnerud
Inspired by miradulo and fix a number conversion problem:
受miradulo启发并修复一个数字转换问题:
import pandas as pd
data_xls = pd.read_excel('excelfile.xlsx', 'Sheet2', dtype=str, index_col=None)
data_xls.to_csv('csvfile.csv', encoding='utf-8', index=False)
Can drop 'Sheet2' if there is one sheet. dtype=str to avoid number conversion.
如果只有一张纸,则可以删除“Sheet2”。dtype=str 以避免数字转换。