【问题标题】:how to add conditional counter to pandas dataframe如何向熊猫数据框添加条件计数器
【发布时间】:2021-12-16 15:49:35
【问题描述】:

我有一个如下图所示的数据框:

id  date       notify
3   04/09/2019  no
3   30/10/2019  yes
3   03/05/2020  no
3   05/09/2020  no
3   31/10/2020  yes
3   03/11/2020  no
5   03/09/2019  no
5   27/10/2019  yes
5   02/05/2020  no

我想在每次“通知”为“是”时创建一个计数器组编号。 然后我想将相同的数字应用于“通知”将始终为“否”的下一行。

应该是这样的:

id  date       notify time_group
3   04/09/2019  no       
3   30/10/2019  yes       1
3   03/05/2020  no        1
3   05/09/2020  no
3   31/10/2020  yes       2
3   03/11/2020  no        2
5   03/09/2019  no
5   27/10/2019  yes       3
5   02/05/2020  no        3

目前我已经尝试过了,但没有成功:

i = 0
df['time_grp'] = np.nan
for row in df.iterrows():
    if row['notify'] == 'yes':
        row['time_group'] = i
        i += 1

我想知道是否有更适合熊猫的方式来完成此任务?也许利用 cumcount()?我知道我可以使用 shift(-1) 将相同的计数器组号应用于下一行...

【问题讨论】:

  • 你每个人都有两个连续的yes吗?
  • 不,我删除了任何连续的“是”

标签: python pandas time-series


【解决方案1】:

试试:

# mark the `yes` rows
s = df['notify'].eq('yes')


# s.cumsum() enumerate the blocks
# maybe `s.groupby(df['id']).cumsum() if enumeration within id
df['time_group'] = s.cumsum().where(               # use `where` to keep      
     s |                                           # the `yes` rows
     s.groupby(df['id']).shift(fill_value=False)   # and those after
)

【讨论】:

    猜你喜欢
    • 2019-12-21
    • 2019-08-29
    • 1970-01-01
    • 2017-08-21
    • 2021-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-11
    相关资源
    最近更新 更多