如何使用 python 函数和 df 度过空闲的日子

问题描述 投票:0回答:1

我有一个 pandas df,我需要一个函数来返回名称和日期,如果这些值在过去 3 天不在 df 中。

例如我的 df1:

| date       | name           |
| ---------- | -------------- |
| 2022-08-05 | Alex           |
| 2022-08-07 | Alex           |

我试过用函数解决它:

def checker (table, name):
    if len(table[table.names == name]) == 3:
        msg = '\n All good'
    else:
        name_list = [*table['name'].unique()]
        msg = '\n No data for:'
        for name in name_list:
            msg += f'\n {name}'
return msg

但是我怎样才能在味精中为那个缺失的名字添加日期?或者也许可以优化我的功能?

在 ouptup 中,如果我的 df 中没有那天的数据,我需要一条带有名称和日期的消息:

2022-08-06 Alex
python pandas function
1个回答
0
投票

这可以通过聚合函数来完成。

首先,按用户对条目进行分组:

grouped = table.groupby("name")

然后统计条目数,得到每个用户的最后日期(注意:这不是原来的要求)

aggreg = grouped.agg({"name": "count", "date": "max"})

要获取 missing 日期,您需要将

"max"
替换为自定义函数:

aggreg = grouped.agg(
    {"name": "count",
     "date": lambda dates: """code to find the missing
             date in the dates Series for a single user"""})

终于可以过滤那些计数小于3的了:

res = aggreg[aggreg.name < 3]

您的用户将在

res.index
res.date
中的日期。

© www.soinside.com 2019 - 2024. All rights reserved.