根据条件python pandas向数据框添加新行 [英] add new rows to dataframe based on condition python pandas

查看:107
本文介绍了根据条件python pandas向数据框添加新行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

需要根据条件向数据框添加新行.

Need to add new rows to dataframe based on condition.

当前数据框:

在此数据框中,有4列.我想做的是检查时间"列,并检查每个夜班中午夜12点的最近值,并添加两个新行,分别为11:59:59和00:00:01,其中与该值相同最近的数据点.

In this dataframe there are 4 columns. 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.

例如:03-01晚的最接近值(至12PM)是21:46:54.所以需要添加两行,

For examle: Closest value(to 12PM) for 03-01 Night is 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:

样本数据:

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 !!!!!

推荐答案

您可以使用 idxmax()查找每天的最大记录,然后创建日期时间对象.

you can use idxmax() to find the max record per day, then create a datetime 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

这篇关于根据条件python pandas向数据框添加新行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆