Home > front end >  How can I apply maths to a pandas dataframe over different rows and columns
How can I apply maths to a pandas dataframe over different rows and columns

Time:10-17

I have this dataframe

How can I apply math to this across rows and columns? Meaning how can I check to see if df['High']at row 'A' is higher than df['Low']at row 'C' and apply this to all rows of a much larger dataframe.

So if this df had 1000 rows how would I apply this formula to all rows?

CodePudding user response:

The first step you want to do can be done by df.loc["A", "High"] > df.loc["C", "Low"]. To apply this to all rows you could do something like below:

for i in range(2, len(df)):
    print(df["High"][i-2] > df["Low"][i])

I'm sure there are better ways to do it, but this would work.

CodePudding user response:

you can use shift operation on column to shift the rows up/down

`df['High'] > df['Low'].shift(-2)`

To elaborate what's going on, run below commands

df = pd.DataFrame(np.random.randn(5,4), list('ABCDE'), ['Open', 'High', 'Low', 'Close'])
df['Low_shiftup'] = df['Low'].shift(-2)
df.head()
df['High'] > df['Low_shiftup']
  • Related