0

I am looking how to create an if function that will select a row above another row where ColumnX is equal to the number 13.

Here is the code I have

if df.attrib.get("Column_Name") in ['13']:

I know this means that if column name "Column_Name" = 13 then ... but I want it to be if "Column_Name" 1 row below is equal to 13 then ...

sam2611
  • 455
  • 5
  • 15
DBuck
  • 21
  • 4
  • 1
    Sorry but could you explain what do you mean by this sentence "but I want it to be if Column_Name 1 row below is equal to 13,14,15" – sam2611 Jul 14 '21 at 14:19
  • I guess to simplify it I want to select the row above another row where a column is equal to 13 – DBuck Jul 14 '21 at 14:24
  • 2
    Welcome to SO. Please provide an [mre] - which should include example data (emphasis on minimal). [How to make good reproducible pandas examples](https://stackoverflow.com/questions/20109391/how-to-make-good-reproducible-pandas-examples) – wwii Jul 14 '21 at 14:25
  • [Indexing and selecting data](https://pandas.pydata.org/docs/user_guide/indexing.html) (Pandas User guide). – wwii Jul 14 '21 at 14:26

2 Answers2

1

You can use simple Pandas Condition:

import pandas as pd
# i created my own dataframe for testing
df = pd.DataFrame({'numbers':[1,2,13,4,5,13,6]})

# use simple condition to get the index of the element then access the element by index
df.iloc[df[df["numbers"]==13].index-1]

+output:

    numbers
1   2
4   5
Navin Seab
  • 83
  • 1
  • 8
0

You can find the columns using pandas .shift function and a .loc

>>> import pandas
>>> df = pandas.DataFrame({'condition':[1,3,4,3,2,13,3]})
>>> df
           condition
0          1
1          3
2          4
3          3
4          2
5         13
6          3
>>> df["condition_rolled"] = df['condition'].shift(-1)
>>> df
           condition  condition_rolled
0          1               3.0
1          3               4.0
2          4               3.0                                                                                                                               3          3               2.0
4          2              13.0
5         13               3.0
6          3               NaN
>>> df.loc[(df["condition_rolled"] == 13.0)]
           condition  condition_rolled
4          2              13.0                                                                                                                               
Tom S
  • 591
  • 1
  • 5
  • 21