得到了日期时间索引。现在如何让这些记录达到 excel?

Got DatetimeIndex. Now how do I get these records to excel?

目标: 从 excel 文件中,我想获取日期在某个范围内的所有记录,并将它们写入新的 excel 文件。我正在使用的 infile 有 500K+ 行和 21 列。

我尝试过的: 我已经将 infile 读取到 Pandas 数据帧,然后返回了 DatetimeIndex。如果我打印 range 变量,我会得到所需的记录。

import pandas as pd

in_excel_file = r'path\to\infile.xlsx'
out_excel_file = r'path\to\outfile.xlsx'

df = pd.read_excel(in_excel_file)
range = (pd.date_range(start='1910-1-1', end='2021-1-1'))
print(range)

##prints
DatetimeIndex(['1990-01-01', '1990-01-02', '1990-01-03', '1990-01-04',
               '1990-01-05', '1990-01-06', '1990-01-07', '1990-01-08',
               '1990-01-09', '1990-01-10',
               ...
               '2020-12-23', '2020-12-24', '2020-12-25', '2020-12-26',
               '2020-12-27', '2020-12-28', '2020-12-29', '2020-12-30',
               '2020-12-31', '2021-01-01'],
              dtype='datetime64[ns]', length=11324, freq='D')

我遇到问题的地方是将上面的 DatetimeIndex 放到输出文件中。以下给了我一个错误:

range.to_excel(out_excel_file, index=False)
AttributeError: 'DatetimeIndex' object has no attribute 'to_excel'

我很确定写入 excel 时它必须是 dataframe。所以,我的问题是如何将 range 变量获取到数据框对象?

Goal: From an excel file, I want to get all the records which have dates that fall within a range and write them to a new excel file. The infile I'm working with has 500K+ rows and 21 columns.

您可以对 select 原始 DataFrame 中所需的数据使用索引操作,并将结果保存在 Excel 文件中。

为此,您首先需要检查原始 DataFrame 中的日期列是否已转换为 datetime/date 对象:

import numpy as np

date_column = "date"  # Suppose this is your date column name
if not np.issubdtype(df[date_column].dtype, np.datetime64):
    df.loc[:, date_column] = pd.to_datetime(df[date_column], format="%Y-%m-%d")

现在您可以使用常规索引操作来获取您需要的所有值:

mask = (df[date_column] >= '1910-01-01') & (df[date_column] <= '2021-01-01')  # Creates mask for date range
out_dataframe = df.loc[mask]  # Here we select the indices using our mask
out_dataframe.to_excel(out_excel_file)

您可以尝试在将 DatetimeIndex 写入 Excel 之前从 DatetimeIndex 创建数据框,如下所示:

range_df = pd.DataFrame(index=range).rename_axis(index='range').reset_index()

或者按照@guimorg 的建议,我们也可以这样做:

range_df = range.to_frame(index=False, name='range')

然后,继续您的代码将其写入 Excel:

range_df.to_excel(out_file, index=False)