我有两个数据框-一个具有每日索引,一个具有不规则索引。我想对不规则的地方进行日常抽样,但是使用总和作为fill
方法。
例如,
df0 = pd.DataFrame(index=pd.date_range(start='2018-03-10', periods=10))
df0['dat'] = 1
# df1 has "missing" days
df1 = df0.iloc[[0,3,4,6,9]]
df0 = df0.reindex(df1, method='sum') # NOT A REAL METHOD
我正在寻找的结果df0
是:
2018-03-10 1
2018-03-13 3 # sum of indices 1 and 2 and 3
2018-03-14 1
2018-03-16 2 # sum of 5 and 6
2018-03-19 3 # sum of 7, 8, and 9
你需要创建组骨料sum
使用Index.to_series
与reindex
和前进和后退填充NAN
S:
df0 = pd.DataFrame(index=pd.date_range(start='2018-03-10', periods=12))
df0['dat'] = 1
a = df1.index.to_series().reindex(df0.index).bfill().ffill()
print (a)
2018-03-10 2018-03-10
2018-03-11 2018-03-13
2018-03-12 2018-03-13
2018-03-13 2018-03-13
2018-03-14 2018-03-14
2018-03-15 2018-03-16
2018-03-16 2018-03-16
2018-03-17 2018-03-19
2018-03-18 2018-03-19
2018-03-19 2018-03-19
2018-03-20 2018-03-19 #<-replace last NaNs by ffill()
2018-03-21 2018-03-19 #<-replace last NaNs by ffill()
Freq: D, dtype: datetime64[ns]
fin = df0.groupby(a).sum()
print (fin)
dat
2018-03-10 1
2018-03-13 3
2018-03-14 1
2018-03-16 2
2018-03-19 5
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句