筛选在所有PortDt日期中均存在记录的DataFrame数据
筛选在所有日期都出现的贷款记录
给定如下DataFrame:
import pandas as pd df = pd.DataFrame({ 'PortDt': ['2022-01-31', '2022-02-28', '2022-02-28', '2022-03-31', '2022-03-31'], 'loannum': ['111', '111', '222', '111', '333'] })
要筛选出在所有不同PortDt日期中均出现的loannum对应的所有记录,可按以下步骤实现:
统计数据中所有不同的日期数量:
total_unique_dates = df['PortDt'].nunique()按
loannum分组,统计每个贷款号覆盖的不同日期数:loan_date_coverage = df.groupby('loannum')['PortDt'].nunique()筛选出覆盖了全部日期的贷款号:
valid_loans = loan_date_coverage[loan_date_coverage == total_unique_dates].index从原DataFrame中提取这些有效贷款号的所有记录,并按日期排序:
result = df[df['loannum'].isin(valid_loans)].sort_values('PortDt').reset_index(drop=True)
执行后得到的结果如下:
PortDt loannum 0 2022-01-31 111 1 2022-02-28 111 2 2022-03-31 111
内容的提问来源于stack exchange,提问作者gernworm
相关产品推荐
相关产品推荐

