在Python中使用Pandas将CSV转换为Excel

在Python中使用Pandas将CSV转换为Excel

Pandas可以读取、过滤和重新排列大大小小的数据集,并以一系列的格式输出,包括Excel。在这篇文章中,我们将处理将.csv文件转换为excel(.xlsx)的问题。
Pandas提供了ExcelWriter类,用于将数据框架对象写入excel表格中。
语法:

final = pd.ExcelWriter('GFG.xlsx')
Python

示例:
样本CSV文件:

在Python中使用Pandas将CSV转换为Excel

import pandas as pd
 
 
# Reading the csv file
df_new = pd.read_csv('Names.csv')
 
# saving xlsx file
GFG = pd.ExcelWriter('Names.xlsx')
df_new.to_excel(GFG, index=False)
 
GFG.save()
Python

输出:

在Python中使用Pandas将CSV转换为Excel

方法 2:

read函数用于向pandas读取数据,to方法用于存储数据。to_excel() 方法将数据存储为一个excel文件。在这里的例子中,sheet_name被命名为乘客,而不是默认的Sheet1。通过设置_index=False ,行索引标签不会被保存在电子表格中。

import pandas as pd
 
# The read_csv is reading the csv file into Dataframe
 
df = pd.read_csv("./weather_data.csv")
 
# then to_excel method converting the .csv file to .xlsx file.
 
df.to_excel("weather.xlsx", sheet_name="Testing", index=False)
 
# This will make a new "weather.xlsx" file in your working directory.
# This code is contributed by Vidit Varshney
Python

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册