[英]Pandas/Python add a row based on condition
YY_MM_CD customerid pol_no type WE WP
2019-07 15680 1313145 new 3 89
2020-01 14672 1418080 renwd -8 223
2019-01 15681 1213143 new 4 8
2019-01 15683 1213344 new -6 3
2019-03 14678 1418280 renwd -66 -7
现在 。 我有一些 x 年的数据,我正在拍摄 19-20 的快照。 假设如果此快照中的客户在 2019 年 1 月 11 日支付了保费,则该客户在 2020 年 1 月 11 日没有支付保费,因此该记录将不是他们的数据。 我需要为那个客户创建一个虚拟记录。 喜欢这个客户 ID 15681 并保持他们的 WE 和 WP 为 0 0 因为客户没有付款
YY_MM_CD customerid pol_no type WE WP
2019-07 15680 1313145 new 3 89
2020-01 14672 1418080 renwd -8 223
2019-01 15681 1213143 new 4 8
2020-01 15681 1213143 new 0 0
2019-03 14678 1418280 renwd -66 -7
不要创建虚拟数据点。 在每个客户 ID 旁边写下到期日期。 然后在访问数据时只需检查当前数据是否在到期日期之前。
更简单更干净
如果您想按照您的要求执行操作(根据条件添加行或列):
例如。
new_df = pd.DataFrame()
df = YOURDATA
groups = df.groupby("customerid")
for group in groups:
if len(group) < 2: #your condition
df2 = pd.DataFrame( ADD YOUR DATA HERE)
new_df.append(df2, ignore_index=True)
最后,您可以将 new_df 和 df 与 concat 结合起来: https ://pandas.pydata.org/pandas-docs/stable/user_guide/merging.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.