Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find a common value using if statement

I am still a beginner in python. I am trying to find a common value with if statement,

import pandas as pd

df = pd.read_csv("data.csv")

for n in range(2, len(df)):
    if df.loc[n].isin([2]).any():
        if df.loc[n-1].isin([1]).any():
            print("Yes")

n += 1
A B
1 3
2 3
1 8
1 2
3 5
2 7

I want it to be printed "Yes" if every time 2 is in n and 1 is in n-1 until the end of data. not just if it matches once. If ever 2 is in n and n-1 doesn't have any value 1, then it won't be printed. For example the above table won't be printed as not all 2 in n doesn't have 1 in n-1

like image 641
Kan Avatar asked Jan 22 '26 16:01

Kan


2 Answers

i would give a try to this code:

res = (df.loc[df["A"]==2].index-1).isin(df.loc[df["A"]==1].index).all()

then print your dataframe bases on boolean value in res.

like image 96
strawdog Avatar answered Jan 25 '26 05:01

strawdog


You can solve this efficiently with a vector operation. You need to find:

  • all rows in which there is at least one "2" with eq + any
  • access the previous rows with shift
  • test again for those if any value is "1"
  • check if all such rows are True
out = df.shift()[df.eq(2).any(axis=1)].eq(1).any(axis=1).all()

Output: False

To better understand how this works, let's define the following intermediates:

m1 = df.eq(2).any(axis=1)
m2 = df.shift()[m1].eq(1).any(axis=1)

Which gives us:

   A  B     m1     m2
0  1  3  False    NaN
1  2  3   True   True  # previous values are 1, 3 -> True
2  1  8  False    NaN
3  1  2   True   True  # previous values are 1, 8 -> True
4  3  5  False    NaN
5  2  7   True  False  # previous values are 3, 5 -> False
like image 24
mozway Avatar answered Jan 25 '26 05:01

mozway



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!