根据 Pandas 中的开始日期和结束日期填充行,包括开始日期

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

我目前遇到了跨越 Pandas 中开始日期与结束日期范围给出的行的问题,但还需要提供开始日期,而不仅仅是差异。 我尝试了这个解决方案link

感谢@Shubham Sharma 帮助解决了这个问题,并感谢最初提出这个问题的@Pandinus。

这可以跨越两个日期差异的行,我只需要在新列上添加开始日期,但我没有那么幸运。

我应该继续使用此代码还是有人会提出不同的建议以获得良好的结果?

d = df['date_end'].sub(df['date_start']).dt.days
df1 = df.reindex(df.index.repeat(d))
i = df1.groupby(level=0).cumcount() + 1

df1['date'] = df1['date_start'] + pd.to_timedelta(i, unit='d')

从该帖子中获取示例,这就是我需要的结果:

Id  num color   date_start  date_end    Dailydate
0   aa0 blue    1/1/2022    1/2/2022    1/1/2022
0   aa0 blue    1/1/2022    1/2/2022    1/2/2022
1   aa1 red     1/1/2022    1/4/2022    1/1/2022
1   aa1 red     1/1/2022    1/4/2022    1/2/2022
1   aa1 red     1/1/2022    1/4/2022    1/3/2022
1   aa1 red     1/1/2022    1/4/2022    1/4/2022
2   aa2 yellow  1/7/2022    1/9/2022    1/7/2022
2   aa2 yellow  1/7/2022    1/9/2022    1/8/2022
2   aa2 yellow  1/7/2022    1/9/2022    1/9/2022
3   aa3 green   1/12/2022   1/14/2022   1/12/2022
3   aa3 green   1/12/2022   1/14/2022   1/13/2022
3   aa3 green   1/12/2022   1/14/2022   1/14/2022

我尝试过使用 cumcount 函数,甚至先添加列,然后使用 +1 读取它,但这给了我日期时间问题。 而且我也认为这不是最好的方法。

有什么想法吗?谢谢。

python pandas dataframe timedelta
1个回答
0
投票

IIUC,您可以在

apply
创建日期范围上使用
axis=1
explode
:

df["Dailydate"] = df.apply(
    lambda row: pd.date_range(row["date_start"], row["date_end"]), axis=1
)
df = df.explode("Dailydate").reset_index(names="Id")
    Id   id  number   color date_start   date_end  Dailydate
0    0  aa0       1    blue 2022-01-01 2022-01-02 2022-01-01
1    0  aa0       1    blue 2022-01-01 2022-01-02 2022-01-02
2    1  aa1       2     red 2022-01-01 2022-01-04 2022-01-01
3    1  aa1       2     red 2022-01-01 2022-01-04 2022-01-02
4    1  aa1       2     red 2022-01-01 2022-01-04 2022-01-03
5    1  aa1       2     red 2022-01-01 2022-01-04 2022-01-04
6    2  aa2       2  yellow 2022-01-07 2022-01-09 2022-01-07
7    2  aa2       2  yellow 2022-01-07 2022-01-09 2022-01-08
8    2  aa2       2  yellow 2022-01-07 2022-01-09 2022-01-09
9    3  aa3       1   green 2022-01-12 2022-01-14 2022-01-12
10   3  aa3       1   green 2022-01-12 2022-01-14 2022-01-13
11   3  aa3       1   green 2022-01-12 2022-01-14 2022-01-14
© www.soinside.com 2019 - 2024. All rights reserved.