首页 > 解决方案 > 在 Pandas 列中有 NaN 的地方,我想用 1 替换,但需要对 1 求和的 Totals 除外

问题描述

在月回报列中,我需要用 1 替换 NaN,但类别列中的 ros 用“TOTAL”替换。我需要在前一个“TOTAL”行之后将 1 加起来。分组行的长度(按日期和帐户)可能因长度而异。

Return Date    Account      Category    Month Return
 7/31/2003      abcdef       BOND        NaN
 7/31/2003      abcdef       CASH        NaN
 7/31/2003      abcdef       EQUITY      NaN
 7/31/2003      abcdef       TOTAL       Nan
 7/31/2003      ghijkl       BOND        0.25
 7/31/2003      ghijkl       CASH        0.25
 7/31/2003      ghijkl       EQUITY      1.25
 7/31/2003      ghijkl       TOTAL       1.75
 7/31/2003      mnopqr       BOND        NaN
 7/31/2003      mnopqr       CASH        NaN
 7/31/2003      mnopqr       EQUITY      NaN
 7/31/2003      mnopqr       REAL        NaN
 7/31/2003      mnopqr       TOTAL       Nan

希望它看起来像这样:

Return Date    Account      Category    Month Return
 7/31/2003      abcdef       BOND        1
 7/31/2003      abcdef       CASH        1
 7/31/2003      abcdef       EQUITY      1
 7/31/2003      abcdef       TOTAL       3
 7/31/2003      ghijkl       BOND        0.25
 7/31/2003      ghijkl       CASH        0.25
 7/31/2003      ghijkl       EQUITY      1.25
 7/31/2003      ghijkl       TOTAL       1.75
 7/31/2003      mnopqr       BOND        1
 7/31/2003      mnopqr       CASH        1
 7/31/2003      mnopqr       EQUITY      1
 7/31/2003      mnopqr       REAL        1
 7/31/2003      mnopqr       TOTAL       4

标签: pythonpandas

解决方案


您可以将DataFrame.fillnaDataFrame.loc一起使用:

df=df.replace('Nan',np.nan)
c=df['Category'].ne('TOTAL')
df.loc[c,'Month_Return']=df.loc[c,'Month_Return'].fillna(1)
fill=df.groupby('Account')['Month_Return'].apply(lambda x: x.eq(1).cumsum())
df['Month_Return'].fillna(fill,inplace=True)
print(df)

   Return_Date Account Category Month_Return
0    7/31/2003  abcdef     BOND            1
1    7/31/2003  abcdef     CASH            1
2    7/31/2003  abcdef   EQUITY            1
3    7/31/2003  abcdef    TOTAL            3
4    7/31/2003  ghijkl     BOND         0.25
5    7/31/2003  ghijkl     CASH         0.25
6    7/31/2003  ghijkl   EQUITY         1.25
7    7/31/2003  ghijkl    TOTAL         1.75
8    7/31/2003  mnopqr     BOND            1
9    7/31/2003  mnopqr     CASH            1
10   7/31/2003  mnopqr   EQUITY            1
11   7/31/2003  mnopqr     REAL            1
12   7/31/2003  mnopqr    TOTAL            4

推荐阅读