Skip to content
Advertisement

Checking Previous elements in a list with Python and based on the previous element store a value in a new column with Pandas

JavaScript

I have a table which contains 2 columns. the code will check the previous element of list and look for ( Startup / Shutdown ) : Example : if a Crash is after a Startup ; State column will be filled with Startup in front of that Crash as the table below :

Crashes State
Crash in A Startup
Crash in B Shutdown
Crash in C Shutdown
Crash in D Startup
Crash in E Startup
Crash in F Startup
Crash in G Startup
Crash in X Shutdown
Crash in Y Shutdown
Crash in Z Shutdown

the challenge I’m having is that the letters are random each time so i have to use “Crash in” in my code and not specific letters !

Any suggestions on how to do this?

EDIT : Real life example ( each line is an element of a list) :

JavaScript

Code used from @mozway’s Answer :

JavaScript

Output :

JavaScript

Expected Output :

JavaScript

Advertisement

Answer

IIUC, you can use a generator:

JavaScript

output:

JavaScript

input:

JavaScript
updated answer
JavaScript

output:

JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement