gpt4 book ai didi

python - 将一行分成多条记录python

转载 作者:行者123 更新时间:2023-12-05 05:49:03 25 4
gpt4 key购买 nike

我有一个输入数据框如下

Class   Duration    StudentID   Age Startdate   Start Time  Enddate     End Time    TimeDifference
5th XX 20002 5 04/12/2021 17:00:00 04/14/2021 20:00:00 3000

我想根据开始和结束日期将其分成三个不同的行,如下所示。

Class   Duration    StudentID   Age     Startdate   Start Time  Enddate     End Time    TimeDifference
5th XX 20002 5 04/12/2021 17:00:00 04/12/2021 23:59:59 360
5th XX 20002 5 04/13/2021 0:00:00 04/13/2021 23:59:59 1440
5th XX 20002 5 04/14/2021 0:00:00 04/14/2021 20:00:00 1200

我正在尝试使用 python。请帮忙。

Input Output is here

最佳答案

“时差”的值略有不同,但这是一种您可以调整和使用的方法。

第 1 步:您可以使用 melt() 开始您的 id_vars 是除“开始日期”和“结束日期”之外的所有列。

第 2 步:然后,您可以将 index 设置为您的 StartEndDate 列,该列是在熔化数据框后创建的。

第 3 步:然后使用 reindex()您可以添加包含缺失日期的新行。

最后剩下的就是计算时差列并重新排列数据帧以获得最终输出。

我假设您的数据框名为 df:

# Step 1
ids = [c for c in df.columns if c not in ['Startdate','Enddate']]
new = df.melt(id_vars=ids,value_name = 'StartEndDate').drop('variable',axis=1)
new.loc[new.StartEndDate.isin(df['Startdate'].tolist()),'Start Time'] = "00:00"

print(new)
Class Duration StudentID Age Start Time End Time TimeDifference \
0 5th XX 20002 5 00:00 20:00 3000
1 5th XX 20002 5 17:00 20:00 3000

StartEndDate
0 04/12/2021
1 04/14/2021

# Step 2
new['StartEndDate'] = pd.to_datetime(new['StartEndDate']).dt.date
new.set_index(pd.DatetimeIndex(new.StartEndDate),inplace=True)

# Step 3
final = new.reindex(pd.date_range(new.index.min(),new.index.max()), method='ffill').reset_index()\
.rename({'index':'Startdate'},axis=1).drop('StartEndDate',axis=1)
final['Enddate'] = final['Startdate']

final['TimeDifference'] = (final['End Time'].str[:2].astype(int) - final['Start Time'].str[:2].astype(int))*60

打印:

final = final[['Class','Duration','StudentID','Age','Startdate','Start Time','Enddate','End Time','TimeDifference']]

Class Duration StudentID Age Startdate Start Time Enddate End Time \
0 5th XX 20002 5 2021-04-12 00:00 2021-04-12 20:00
1 5th XX 20002 5 2021-04-13 00:00 2021-04-13 20:00
2 5th XX 20002 5 2021-04-14 17:00 2021-04-14 20:00

TimeDifference
0 1200
1 1200
2 180

我认为您的问题中缺少一些信息,因此我建议逐行运行并进行必要的调整以适应您的任务。

关于python - 将一行分成多条记录python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70720224/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com