gpt4 book ai didi

python - 如何在多索引 Pandas 中按次日值填充缺失值?

转载 作者:行者123 更新时间:2023-12-04 07:24:56 24 4
gpt4 key购买 nike

我有一个数据框:

                    stock   price
symbol DATE
ABC 2014-01-02 000001 6
2014-01-03 000001 7
2014-01-06 000001 8
XYZ 2015-07-02 000002 9
2015-07-04 000002 10
2015-07-06 000002 11
我想获得一个新的数据框
                    stock   price
symbol DATE
ABC 2014-01-02 000001 6
2014-01-03 000001 7
2014-01-04 000001 8
2014-01-05 000001 8
2014-01-06 000001 8
XYZ 2015-07-02 000002 9
2015-07-03 000002 10
2015-07-04 000002 10
2015-07-05 000002 11
2015-07-06 000002 11
怎么做?

最佳答案

GroupBy.apply 中使用自定义函数与 Series.reindex :

f = lambda x: x.reindex(pd.date_range(x.index.min(), x.index.max(), name='DATE')).bfill()
df = df.reset_index(level=0).groupby(['symbol','stock'])['price'].apply(f).reset_index()
print (df)
symbol stock DATE price
0 ABC 000001 2014-01-02 6
1 ABC 000001 2014-01-03 7
2 ABC 000001 2014-01-04 8
3 ABC 000001 2014-01-05 8
4 ABC 000001 2014-01-06 8
5 XYZ 000002 2015-07-02 9
6 XYZ 000002 2015-07-03 10
7 XYZ 000002 2015-07-04 10
8 XYZ 000002 2015-07-05 11
9 XYZ 000002 2015-07-06 11

关于python - 如何在多索引 Pandas 中按次日值填充缺失值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68270438/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com