背景:
我使用 pyodbc 下载了以下数据框,日期在 1999 年到 2015 年之间:
CEISales.head(10)
Out[194]:
Order_DateC RegionC SalesC
0 2014-01-30 Domestic 3530.00
1 2011-10-11 Domestic 136.00
2 1999-01-13 Domestic 30.00
3 1999-01-13 Domestic 55615.00
4 1999-01-13 Domestic 440.00
5 1999-01-13 Domestic 94.00
6 1999-01-05 Domestic 612.00
7 1999-01-14 Domestic 1067.00
8 1999-01-14 Domestic 26345.05
9 1999-01-15 Domestic 161858.72
然后我过滤了大于 2010-01-01 的所有日期的数据并按升序日期排序:
CEIFilter = CEISales[CEISales['Order_DateC'] > '2010-01-01']
CEITest = CEIFilter.sort('Order_DateC')
CEITest.head(5)
Out[199]:
Order_DateC RegionC SalesC
18156 2010-01-04 Foreign 450.0
18155 2010-01-04 Domestic 1990.4
18154 2010-01-04 Domestic 37477.0
18152 2010-01-04 Domestic 0.0
18153 2010-01-04 Domestic 783.0
然后我使用 pandas 的 date_range 函数创建了一个日期索引,其值介于 2010-01-01 和今天之间:
date_index = pd.date_range(start='2010-01-01', end='2015-12-23' , freq='d')
并重新索引数据框
CEIFinal= CEITest.reindex(date_index)
我的问题是,当我重新索引数据框时,所有数据都被删除了:
CEIFinal.head(5)
Out[206]:
Order_DateC RegionC SalesC
2010-01-01 NaT NaN NaN
2010-01-02 NaT NaN NaN
2010-01-03 NaT NaN NaN
2010-01-04 NaT NaN NaN
2010-01-05 NaT NaN NaN
从过滤后的原始数据框中可以看到 2010-04-01 上有交易
CEITest[CEITest['Order_DateC'] == '2010-01-04']
Out[210]:
Order_DateC RegionC SalesC
18156 2010-01-04 Foreign 450.0
18155 2010-01-04 Domestic 1990.4
18154 2010-01-04 Domestic 37477.0
18152 2010-01-04 Domestic 0.0
18153 2010-01-04 Domestic 783.0
问题 如何使用此日期范围重新索引此数据框并保留所有原始值?我正在尝试在来自不同数据库的几个不同数据帧上创建一个公共(public)索引,以将它们添加到一个聚合数据帧中。非常感谢您的帮助。谢谢!
请您参考如下方法:
当索引不是 DatetimeIndex 时,您正在按 DatetimeIndex 重新编制索引:
Order_DateC RegionC SalesC
18156 2010-01-04 Foreign 450.0
18155 2010-01-04 Domestic 1990.4
18154 2010-01-04 Domestic 37477.0
18152 2010-01-04 Domestic 0.0
18153 2010-01-04 Domestic 783.0
因此有 NaN 和 NaT。
也许您想使 Order_DateC 成为索引:
df = df.set_index("Order_DateC")
然后到resample .
如果重新编制索引,您将丢失具有重复日期的行。
