提问人:Talha Ahmad 提问时间:11/17/2023 更新时间:11/17/2023 访问量:36
数据框导出到 Excel 的格式不是所需的格式
Data Frame Export to Excel is not in the Desired Format
问:
当我尝试将数据框导出到我的输出 .xlsx 文件中时,日期格式为 YYYY-MM-DD HH:MM:SS。我想要的输出是 YYYY-MM-DD(或没有时间)。这是我的代码:
import pandas as pd
# create a DataFrame
df = pd.read_excel(r'C:\Users\Python\data.xlsx')
#define output path
path = r"C:\Users\Python\output.xlsx"
#print to console to check if read is good
print(df)
#process new data frame from original
CasesperDay_df = df.groupby('Date').agg({'cases':'sum'})
#print to console to check for desired output
print (CasesperDay_df)
#export processed data to output file
CasesperDay_df.to_excel(r"C:\Users\Python\output.xlsx", sheet_name = 'Cases per Day')
以下是具有不需要的结果的输出:
这是我希望看到的输出:
这就是我尝试过的
插入将日期格式从 datetime 转换为日期的命令
import pandas as pd
# create a DataFrame
df = pd.read_excel(r'C:\Users\Python\data.xlsx')
#define output path
path = r"C:\Users\Python\output.xlsx"
#print to console to check if read is good
print(df)
#process new data frame from original
CasesperDay_df = df.groupby('Date').agg({'cases':'sum'})
#print to console to check for desired output
print (CasesperDay_df)
#export processed data to output file
CasesperDay_df.to_excel(r"C:\Users\Python\output.xlsx", sheet_name = 'Cases per Day')
#convert date to desired result
CasesperDay_df['Date'] = pd.to_datetime(CasesperDay_df['Date']).dt.date
答:
1赞
Talha Ahmad
11/17/2023
#1
想通了
只需要先将原始数据框转换为正确的日期格式
df['Date'] = pd.to_datetime(df['Date']).dt.date
1赞
Corralien
11/17/2023
#2
您可以使用自定义日期时间格式作为引擎:xlsxwriter
# Install xlsxwriter: pip install xlsxwriter
with pd.ExcelWriter(r'C:\Users\Python\output.xlsx',
datetime_format='M/D/YYYY',
engine='xlsxwriter') as xlsx:
CasesperDay_df.to_excel(xlsx, sheet_name='Cases per Day')
评论