1

I have a datafarme let's say something like this:

| ColumnX        |
| -------------- |
| Hi             |
| + Open         |
| How are you    |
| NAN            |
| Something      |
| something      |
| HEY            |
| + Open         |

now I need to go through the rows checking their values. If the row value is "+ Open" then select the previous row value and put it into a list. so far this is what I've done but I couldn't figure out how to take the previous value-

ilist=[]
for i in df["ColumnX"]:
    if i == '+ Open':
        ilist.append(i)
0

3 Answers 3

3

Create the mask for values, shift the mask passing -1, then fill NA by False which is basically the last row, then use this mask to get the values and finally create list out of the values:

>>> df.loc[df['ColumnX'].eq('+ Open').shift(-1).fillna(False) ,'ColumnX'].to_list()

# Output:
['Hi', 'HEY']
Sign up to request clarification or add additional context in comments.

Comments

0

Maybe something like this:

ilist=[]
for i in range(0,len(df["ColumnX"])):
    if df["ColumnX"][i] == '+ Open':
        ilist.append(df["ColumnX"][i-1])

Comments

0

You could use enumerate and acces the previous value by index:

import pandas as pd

df = pd.DataFrame(["Hi", "+ Open", "How are you", "NAN", "Something", "Something", "HEY","+ Open"], columns=["ColumnX"])

ilist = []

for i, value in enumerate(df["ColumnX"]):
    if value == "+ Open" and i>0: # check if i>0 to prevent out of index error
        ilist.append(df.at[i-1, "ColumnX"])
        
print(ilist)

Out:

['Hi', 'HEY']

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.