gpt4 book ai didi

python Pandas 方法 "ffill"

转载 作者:太空宇宙 更新时间:2023-11-03 23:53:38 26 4
gpt4 key购买 nike

这是我的初始df

       China  USA
2009 NaN -9
2010 1.2 8
2011 1.5 NaN
2014 5.0 NaN
2015 NaN 8

然后我用reindex方法添加了一些索引

frame2=frame1.reindex([2009,2010,2011,2012,2013,2014,2015,2016],method="ffill")

我希望 frame2 从

       China  USA
2009 NaN -9
2010 1.2 8
2011 1.5 NaN
2012 NaN NaN
2013 NaN NaN
2014 5.0 NaN
2015 NaN 8
2016 NaN NaN

       China  USA
2009 NaN -9
2010 1.2 8
2011 1.5 8
2012 1.5 8
2013 1.5 8
2014 5.0 8
2015 5.0 8
2016 5.0 8

但它回来了

       China  USA
2009 NaN -9
2010 1.2 8
2011 1.5 NaN
2012 1.5 NaN
2013 1.5 NaN
2014 5.0 NaN
2015 NaN 8
2016 NaN 8

它只填充了我 df 的一些条目..

最佳答案

从某种意义上说,它确实是前向填充。将中国NaN2015提前到2016,从2011 > 到 2013美国

相反,在 reindex 之后执行 ffill

frame1.reindex([2009,2010,2011,2012,2013,2014,2015,2016]).ffill()

China USA
2009 NaN -9.0
2010 1.2 8.0
2011 1.5 8.0
2012 1.5 8.0
2013 1.5 8.0
2014 5.0 8.0
2015 5.0 8.0
2016 5.0 8.0

进一步说明

# Original

China USA
2009 NaN -9
2010 1.2 8
2011 1.5 NaN
2014 5.0 NaN
2015 NaN 8

您的方法完成了预期的工作。如果获取在现有索引中找到的值并将它们传播到所有新索引。

frame1.reindex([2009,2010,2011,2012,2013,2014,2015,2016],method="ffill")

China USA
2009 NaN -9.0
2010 1.2 8.0
2011 1.5 NaN <- From Original
2012 1.5 NaN <- And forward filled
2013 1.5 NaN <- And here
2014 5.0 NaN <- was there in original
2015 From Original -> NaN 8.0
2016 And forward filled -> NaN 8.0

关于 python Pandas 方法 "ffill",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58563281/

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