python - 在 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
解决方案
您可以将DataFrame.fillna与DataFrame.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
推荐阅读
- php - Laravel Passport 多重身份验证
- optimization - LCP pageSpeed和一个JS滑块,如何优化?
- c# - 如何从数据库中填充 ASP.NET 实体框架中的列表
- python - 有没有办法从应用程序中的代码安装 python 库?
- c# - Discord.Net 如何从消息中获得反应
- sql-server - 在 SQL Server 中将字符串数据从行转换为列
- spring-boot - 输入字段中的默认值与 thymeleaf 中的文本区域(春季启动)
- python - Python,在类中的所有对象中搜索关键字,返回 true
- flutter - 看到打开的应用程序时不显示颤振应用程序名称
- javascript - 带有 JS 组件的 TS 中缺少另一种类型