如何根据日期更改df的结构

huangapple go评论62阅读模式
英文:

How to change the structure of df according date

问题

我最初的pandas数据框如下所示:

ID 参数 开始日期 结束日期
1 4 2023年05月05日 2023年05月07日
2 2 2023年05月05日 2023年05月06日
3 1 2023年05月08日 2023年05月09日

能否从数据框中获得以下结构?实际上,我想展开时间段。

ID 参数 日期
1 4 2023年05月05日
1 4 2023年05月06日
1 4 2023年05月07日
2 2 2023年05月05日
2 2 2023年05月06日
3 1 2023年05月08日
3 1 2023年05月09日
英文:

My initial pandas df looks as follows:

ID Parameter Start End
1 4 05.05.2023 07.05.2023
2 2 05.05.2023 06.05.2023
3 1 08.05.2023 09.05.2023

Is it possible to get the following structure out of the dataframe? In fact I want to unpivot the time period.

ID Parameter Date
1 4 05.05.2023
1 4 06.05.2023
1 4 07.05.2023
2 2 05.05.2023
2 2 06.05.2023
3 1 08.05.2023
3 1 09.05.2023

答案1

得分: 3

将两列转换为日期时间,使用 to_datetime 函数,通过 Index.repeat 创建新行,将差值列转换为天数,使用 Series.dt.days,然后使用 GroupBy.cumcount 计算最后使用计数器,将其转换为天的时间差,添加到 Start 列中,使用 to_timedeltaDataFrame.pop 在使用后移除列:

df['Start'] = pd.to_datetime(df['Start'], dayfirst=True)
df['End'] = pd.to_datetime(df['End'], dayfirst=True)

df = df.loc[df.index.repeat(df.pop('End').sub(df['Start']).dt.days + 1)]
td = pd.to_timedelta(df.groupby(level=0).cumcount(), unit='d')

df['Date'] = df.pop('Start').add(td).dt.strftime('%d.%m.%Y')
df = df.reset_index(drop=True)

print(df)
   ID  Parameter        Date
0   1          4  05.05.2023
1   1          4  06.05.2023
2   1          4  07.05.2023
3   2          2  05.05.2023
4   2          2  06.05.2023
5   3          1  08.05.2023
6   3          1  09.05.2023
英文:

Convert both columns to datetimes by to_datetime, create new rows by Index.repeat with subtraction columns converted to days by Series.dt.days, last use counter by GroupBy.cumcount and convert to days timedeltas added to Start column by to_timedelta, DataFrame.pop is remove column after using:

df['Start'] = pd.to_datetime(df['Start'], dayfirst=True)
df['End'] = pd.to_datetime(df['End'], dayfirst=True)

df = df.loc[df.index.repeat(df.pop('End').sub(df['Start']).dt.days + 1)]
td = pd.to_timedelta(df.groupby(level=0).cumcount(), unit='d')

df['Date'] = df.pop('Start').add(td).dt.strftime('%d.%m.%Y')
df = df.reset_index(drop=True)

print (df)
   ID  Parameter        Date
0   1          4  05.05.2023
1   1          4  06.05.2023
2   1          4  07.05.2023
3   2          2  05.05.2023
4   2          2  06.05.2023
5   3          1  08.05.2023
6   3          1  09.05.2023

huangapple
  • 本文由 发表于 2023年5月10日 18:17:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/76217245.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定