python - 从 Pandas 数据框中获取某个日期或之前的值的计数

标签 python pandas dataframe

我有一个日期 2020-05-31 和以下数据框,其中列名是状态:

     rejected revocation    decision         rfe   interview premium    received rfe_response  biometrics withdrawal appeal
196      None       None  2020-01-28        None        None    None  2020-01-16         None        None       None   None
203      None       None  2020-06-20  2020-04-01        None    None  2020-01-03   2020-08-08        None       None   None
209      None       None  2020-12-03  2020-06-03        None    None  2020-01-03         None        None       None   None
213      None       None  2020-06-23        None        None    None  2020-01-27         None  2020-02-19       None   None
1449     None       None  2020-05-12        None        None    None  2020-01-06         None        None       None   None
1660     None       None  2021-09-23  2021-05-27        None    None  2020-01-21   2021-08-17        None       None   None

我想获取每一行所在的最新步骤,以便最新步骤在上面提到的日期或之前 2020-05-31

所以这个输出将是:

196: decision
203: rfe
209: received
213: biometrics
1449: decision
1660: received

甚至可以计数:

{
rejected = 0,
revocation = 0,
decision = 2,
rfe = 1,
interview = 0,
premium = 0,
received = 2,
rfe_response = 0,
biometrics 0 0,
withdrawal = 0,
appeal = 0 
}

目前我正在遍历每一行,我在其中创建一个 {status: date} 的字典,然后我按日期排序,并获取最后一个值(这是一个状态)的键

这很慢,需要很长时间

是否有更简单或更清洁的方法?

注意:每行至少有一个日期,在决策列中

最佳答案

您可以屏蔽哪里日期大于所选日期,然后沿列使用idxmax

dt_max = '2020-05-31'
res = df.where(df.le(dt_max)).astype('datetime64[ns]')\
        .dropna(how='all', axis=0).idxmax(axis=1)
print(res)
# 196       decision
# 203            rfe
# 209       received
# 213     biometrics
# 1449      decision
# 1660      received
# dtype: object

对于每个状态的计数,您可以像这样使用 value_counts

dict_res = res.value_counts().reindex(df.columns, fill_value=0).to_dict()
print(dict_res)
#{'rejected': 0, 'revocation': 0, 'decision': 2, 'rfe': 1, 'interview': 0, 'premium': 0,
# 'received': 2, 'rfe_response': 0, 'biometrics': 1, 'withdrawal': 0, 'appeal': 0}

编辑 感谢@mozway 的评论,我添加了 dropna 来创建 res 以防止该方法在没有任何日期在一行的阈值以下时失败

关于python - 从 Pandas 数据框中获取某个日期或之前的值的计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73532990/

相关文章:

Python dict 使用点符号和链接

python - Flask-RESTful 与 Flask-WTF 表单集成

python - XGBoost 调节 alpha 范围是多少?

python - 地理错误: GeocoderServiceError: HTTP Error 500: Internal Server Error using pandas apply function with str concat

python - 在 Pandas 中迭代生成列名

pandas - 将 spark DataFrame 转换为 pandas DF

python - CharField 不受支持的查找 'istartwith' 或不允许加入该字段

python-3.x - 如何确保 pandas.DataFrame.to_csv 立即刷新

python - Pandas 根据列值组合数据框

python - 按组和特定值之间的数据帧绘制图表