[英]Date error in writing to excel sheet using pandas
I'm using the pandas.DataFrame.to_excel() function to write a few files loaded from databases into an Excel spreadsheet. 我正在使用pandas.DataFrame.to_excel()函数将从数据库加载的一些文件写入Excel电子表格。 The function being used is the following:
使用的功能如下:
def country_reports(countries):
writer = pd.ExcelWriter('country_reports.xlsx')
for country in countries:
df = report(country)
df.to_excel(writer, country)
writer.save()
The report(country)
method just returns a DataFrame
of relevant data for that country. report(country)
方法仅返回该国家/地区的相关数据的数据DataFrame
。 I would like to run this report for multiple countries, and then have each country's data represented in its own tab in Excel. 我想针对多个国家/地区运行此报告,然后将每个国家/地区的数据显示在Excel中自己的标签中。 This would normally be pretty simple, but I have dates earlier than 1900 in some of my DataFrames, which makes it impossible for me to write to Excel, since it throws an error:
这通常很简单,但是我的某些DataFrames中的日期早于1900,这使我无法写Excel,因为它会引发错误:
ValueError: Year not supported by Excel: 1861.
ValueError:Excel不支持的年份:1861。
I had no issues when writing these files as CSVs, so I was curious if there would be some way to create an excel file that had multiple tabs represented by CSVs? 将这些文件作为CSV格式写入时我没有任何问题,所以我很好奇是否可以通过某种方式来创建具有以CSV格式表示的多个标签的Excel文件? If not, is there another way around this issue?
如果不是,是否还有其他方法可以解决此问题?
Do you just need the to show the dates in Excel? 您只需要在Excel中显示日期? If that's the case, could you just convert to a string, something like this.
如果是这样,您可以将其转换为字符串吗?
df['date_col'] = df['date_col'].apply(lambda x: x.date().isoformat())
If you actually need to work with dates in Excel, it's probably best to separate month / day / year into separate columns, something like this: 如果您实际上需要在Excel中使用日期,则最好将月/日/年分隔为单独的列,如下所示:
df['year'] = df['date_col'].apply(lambda x: x.year)
df['day'] = df['date_col'].apply(lambda x: x.day)
df['month'] = df['date_col'].apply(lambda x: x.month)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.