重采样熊猫但有给定日期

时间:2019-08-15 08:39:08

标签: python pandas

我想用datetime作为索引重新采样我的熊猫数据框。当我使用重采样方法时,它将返回带有最后日期索引的重采样日期,该日期并非总是存在于原始数据中。例如,我的原始数据具有2000-01-03〜2005-12-29的数据。但是,当我每年对该数据进行重新采样时,会得到2005-12-31的数据。当我使用concat进行重新采样的数据时,这对我来说是个问题。

Y = price.resample("Y").first()
M = price.resample("M").first()
W = price.resample("W").first()

total = pd.concat([price,W,M,Y], axis=1, sort=False)


#example

price = pd.DataFrame([1315.23, 1324.97, 1376.54, 1351.46, 1343.55, 1369.89, 1380.2 ,
       1371.18, 1359.99, 1340.93, 1312.15, 1322.74, 1305.6 , 1264.74,
       1274.86, 1305.97, 1305.97, 1315.19, 1328.92, 1334.22, 1320.28],
                     index = ['2000-12-01', '2000-12-04', '2000-12-05', '2000-12-06',
               '2000-12-07', '2000-12-08', '2000-12-11', '2000-12-12',
               '2000-12-13', '2000-12-14', '2000-12-15', '2000-12-18',
               '2000-12-19', '2000-12-20', '2000-12-21', '2000-12-22',
               '2000-12-25', '2000-12-26', '2000-12-27', '2000-12-28',
               '2000-12-29'])
price.index = pd.to_datetime(price.index)

price.resample("W").first()
#see how 12-03, 12-10, 12-17, 12-24, 12-31 are not dates that are in the original index

1 个答案:

答案 0 :(得分:0)

您是否考虑过只删除不想要的行? 以下代码将起作用,因为通过重新采样创建的所有行(不在原始索引上)将设置为NaN的值。

price.resample('W').dropna()