在Python中使用 Pandas 将 CSV 转换为 Excel
Pandas 可以读取、过滤和重新排列大小数据集,并以包括 Excel 在内的多种格式输出。在本文中,我们将处理 .csv 文件到 excel (.xlsx) 的转换。
Pandas 提供了 ExcelWriter 类,用于将数据框对象写入 Excel 工作表。
句法:
final = pd.ExcelWriter('GFG.xlsx')
例子:
示例 CSV 文件:
Python3
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()
Python3
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
输出:
方法二:
read_*函数用于向 pandas 读取数据, to_*方法用于存储数据。 to_excel()方法将数据存储为 excel 文件。在此处的示例中,sheet_name 被命名为乘客,而不是默认的 Sheet1。通过设置index=False行索引标签不会保存在电子表格中。
Python3
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