按组用以前的非零单元格值替换空白单元格

时间:2018-12-13 08:23:11

标签: python-3.x pandas pandas-groupby

我有一个数据框,其中包含按产品分类的季度销售额。

edit

我正尝试使用上一季度的结果来填补明智的产品的缺失值。我尝试使用方法选项为“ ffill”的fillna。但它会填充值,而与类别无关。

data=pd.DataFrame({"Product":("A","A","A","A","B","B","B","B","C","C","C","C"),
                   "Quarter":("Q1","Q2","Q3","Q4","Q1","Q2","Q3","Q4","Q1","Q2","Q3","Q4"),
                   "Sales":('N/A','N/A',10,10,'N/A','N/A','N/A','N/A','N/A',30,'N/A',20)
                  })
data["Sales"].replace('N/A',np.NaN,inplace=True)

Product Quarter Sales
0   A   Q1      NaN
1   A   Q2      NaN
2   A   Q3      10.0
3   A   Q4      10.0
4   B   Q1      NaN
5   B   Q2      NaN
6   B   Q3      NaN
7   B   Q4      NaN
8   C   Q1      NaN
9   C   Q2      30.0
10  C   Q3      NaN
11  C   Q4      20.0

获得的o / p:

data["Obtained Sales"]=data["Values"].fillna(method='ffill')

但是如上所述预期的输出:

    Product Quarter Sales   Obtained Sales
0   A   Q1           NaN    NaN
1   A   Q2           NaN    NaN
2   A   Q3           10.0   10.0
3   A   Q4           10.0   10.0
4   B   Q1           NaN    10.0
5   B   Q2           NaN    10.0
6   B   Q3           NaN    10.0
7   B   Q4           NaN    10.0
8   C   Q1           NaN    10.0
9   C   Q2           30.0   30.0
10  C   Q3           NaN    30.0
11  C   Q4           20.0   20.0

如何使用熊猫通过 Groups 用以前的非零值填充空白?

0 个答案:

没有答案