如何用熊猫重塑数据框?

乘风 python 199

原文标题How to reshape dataframe with pandas?

我有一个数据框,其中包含从 2018 年到 2021 年每天的产品销售情况。 Dataframe 包含四列(日期、地点、产品类别和销售)。从前两列(日期、地点)中,我想使用可用数据来填补空白。添加数据后,我想删除 ProductCategory 中没有数据的行。我想在 python pandas 中做。

我的数据集样本如下所示:

My Data frame

我希望数据框看起来像这样:

output dataframe

原文链接:https://stackoverflow.com//questions/71910039/how-to-reshape-dataframe-with-pandas

回复

我来回复
  • dkantor的头像
    dkantor 评论

    将 fillna 与方法 ‘ffill’ 一起使用,将最后一个有效观察值向前传播到下一个有效回填。然后删除包含 NA 的行。

    df['Date'].fillna(method='ffill',inplace=True)
    df['Place'].fillna(method='ffill',inplace=True)
    df.dropna(inplace=True)
    
    2年前 0条评论