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
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.
You can solve this efficiently with a vector operation. You need to find:
eq + anyshiftany value is "1"all such rows are Trueout = 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With