Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.6k views
in Technique[技术] by (71.8m points)

pandas - Repeat the previous row in a database based on conditions using python

I've been stuck on this for a while now. I want to repeat the previous row and iterate the time to one second before the next row (Please see the output below). In my code, I've attempted the task with pandas. The condition for this repeat command should be when "a" column reads "Power_change" AND when the "indicator" column reads above 1 then repeat previous row.

The Input:

a P0 P1 time Indicator
ISALIVE 325 350 10:59:40 31
POWER_CHANGE 200 42333 10:59:52 11
question from:https://stackoverflow.com/questions/65952140/repeat-the-previous-row-in-a-database-based-on-conditions-using-python

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

fileter the data, use index - 1 to get the previous row. then append the origin dataframe.

cond = (df['a'] == "POWER_CHANGE") & (df['Indicator'] > 1)

# calculate the time is 1 second before POWER_CHANGE
obj_time = (pd.to_datetime(df.loc[cond, 'time']) - 
            pd.to_timedelta('00:00:01')).dt.strftime('%T')

# get the previous record before 'POWER_CHANGE'
idx = df.loc[cond].index - 1
dfn = df.loc[idx].copy()

# reassign the time, use `.values` to ignore the index
dfn['time'] = obj_time.values

df.append(dfn).sort_index()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...