Pandas - 在分组数据框中添加具有不同值的行

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

我想为每个组添加行。在每个新行中,必须根据每个组特定的时间间隔更新日期。示例:n_times:对应组的行数,interval_days:对应组按行添加的天数

Id n_times interval_days  date (MM-dd)
1  3       4              03-01  
2  1       4              03-02
3  2       5              03-05
4  4       3              03-07

想要的:

Id n_times interval_days  date (MM-dd)
1  3       4              03-01  
1  3       4              03-05 
1  3       4              03-09 
2  1       4              03-02
3  2       5              03-05
3  2       5              03-10
4  4       3              03-07
4  4       3              03-10
4  4       3              03-13
4  4       3              03-16
python pandas date group-by
2个回答
1
投票

试试这个:

def generate_date_range(n_times: int, interval_days: int, start_date: str, year: str = '2024'):
    return pd.date_range(
        start=f'{year}-{start_date}', periods=n_times, freq=f'{interval_days}D'
    )


result = df.set_index('Id')
result['date (MM-dd)'] = result.apply(lambda x: generate_date_range(*x), axis=1)
result = result.explode('date (MM-dd)')
result['date (MM-dd)'] = result['date (MM-dd)'].dt.strftime('%m-%d')
print(result)
>>>
    n_times  interval_days date (MM-dd)
Id                                     
1         3              4        03-01
1         3              4        03-05
1         3              4        03-09
2         1              4        03-02
3         2              5        03-05
3         2              5        03-10
4         4              3        03-07
4         4              3        03-10
4         4              3        03-13
4         4              3        03-16

0
投票

您可以通过首先基于

n_times
列重复行,然后使用
groupby
函数和
cumcount
方法为您的间隔创建乘数来实现此目的。最后,将此乘数应用于
date
列以获得所需的间隔。请记住首先将
date
列转换为日期时间类型以正确添加天数。这种方法不需要循环遍历每一行,因此对于大型数据集来说非常高效。

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