[英]add new rows to dataframe based on condition python pandas
Need to add new rows to dataframe based on condition.需要根据条件向 dataframe 添加新行。
Current dataframe:当前 dataframe:
In this dataframe there are 4 columns.在这个 dataframe 中有 4 列。 what i want to do ischeck the 'Time' column and check the nearest value for 12PM mid night in every night shift and add two new row as 11:59:59 and 00:00:01 with same values as the that nearest datapoint.我想要做的是检查“时间”列并检查每个夜班午夜 12 点的最接近值,并添加两个新行作为 11:59:59 和 00:00:01,其值与最近的数据点相同。
For examle: Closest value(to 12PM) for 03-01 Night is 21:46:54.例如:03-01 Night 的最接近值(到 12PM)是 21:46:54。 so need to add two rows,所以需要添加两行,
W25 03-01 Night RUNNING 23:59:59
W25 03-01 Night RUNNING 00:00:01
so final expected dataframe should be like this:所以最终预期的 dataframe 应该是这样的:
Sample data:样本数据:
data={'Machine': {0: 'W5', 343: 'W5', 344: 'W5', 586: 'W5', 587: 'W5'}, 'State': {0: 'start', 343: 'STOPPED', 344: 'RUNNING', 586: 'STOPPED', 587: 'MAINT'}, 'Day-Shift': {0: '03-01 Night', 343: '03-01 Night', 344: '03-01 Night', 586: '03-01 Night', 587: '03-01 Night'}, 'Time': {0: Timestamp('2021-03-01 21:00:00'), 343: Timestamp('2021-03-01 22:16:54'), 344: Timestamp('2021-03-01 23:16:54'), 586: Timestamp('2021-03-01 23:48:45'), 587: Timestamp('2021-03-02 02:28:54')}}
Really appreciate your support !!!!!真的很感谢你的支持!!!!!!
you can use idxmax()
to find the max record per day, then create a datetime object.您可以使用idxmax()
查找每天的最大记录,然后创建日期时间 object。
df1 = df.loc[df.groupby([df['Time'].dt.normalize()])['Time'].idxmax()]
df1 = pd.concat([df1] * 2)
df1['Time'] = pd.to_datetime((df1['Time'].dt.normalize().astype(str) + [' 23:59:59', ' 00:00:01']))
print(df1)
Machine State Day-Shift Time
587 W25 MAINT 03-01 Day 2021-03-01 23:59:59
587 W25 MAINT 03-01 Day 2021-03-01 00:00:01
df = pd.concat([df,df1]).sort_index().reset_index(drop=True)
Machine State Day-Shift Time
0 W25 start 03-01 Day 2021-03-01 07:00:00
1 W25 STOPPED 03-01 Day 2021-03-01 07:16:54
2 W25 RUNNING 03-01 Day 2021-03-01 07:16:54
3 W25 STOPPED 03-01 Day 2021-03-01 07:28:45
4 W25 MAINT 03-01 Day 2021-03-01 07:28:54
5 W25 MAINT 03-01 Day 2021-03-01 23:59:59
6 W25 MAINT 03-01 Day 2021-03-01 00:00:01
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.