使用sum作为填充方法对Pandas DataFrame重新索引

曼科夫

我有两个数据框-一个具有每日索引,一个具有不规则索引。我想对不规则的地方进行日常抽样,但是使用总和作为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_seriesreindex和前进和后退填充NANS:

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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

重新索引Pandas中的DataFrame

部分重新索引行索引 Pandas DataFrame

使用复合索引重新索引 DataFrame

重新索引熊猫DataFrame以填充缺少的日期

使用特定的日期时间索引重新索引Pandas Dataframe

用插值重新索引Pandas DataFrame

在pandas DataFrame中重新分配索引

在Pandas DataFrame对象中重新定义索引

子集Pandas DataFrame次要索引和重新分配值

Pandas DataFrame不会重新索引和转置,返回NaN

来自不规则时间序列索引的pandas DataFrame重新采样

Python Pandas:时区转换后重新索引DataFrame

Python Pandas DataFrame从0重新索引某些数据

根据索引中整数的重复集对pandas DataFrame重新排序

使用dict(python3)重新索引熊猫DataFrame

python-“布尔系列键将重新索引以匹配DataFrame索引。从ipykernel导入kernelapp作为应用程序”

如何使用熊猫的重新索引方法“填充”插入数据?

ValueError:将新列分配给pandas DataFrame时,无法从重复的轴重新索引

Pandas DataFrame:沿整数索引重新采样/按n个元素分组

Pandas DataFrame日期时间索引无法在JSON转换和重新转换后幸免

熊猫重新索引以填充日期索引

不使用索引列作为Pandas DataFrame中的变量

重新索引 Pandas 数据框

如何在python的pandas dataframe列中填充静止的数值并将其作为索引?

将pandas系列作为一列添加到多索引的DataFrame填充级别

Python Pandas DataFrame索引

Pandas 使用大于和小于索引重新索引数据框

熊猫重新索引填充缺失的日期

重新索引和填充R数据帧