在Python中使用Pandas将CSV转换为Excel
Pandas可以读取、过滤和重新排列大大小小的数据集,并以一系列的格式输出,包括Excel。在这篇文章中,我们将处理将.csv文件转换为excel(.xlsx)的问题。
Pandas提供了ExcelWriter类,用于将数据框架对象写入excel表格中。
语法:
final = pd.ExcelWriter('GFG.xlsx')
示例:
样本CSV文件:
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()
输出:
方法 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