0

I am trying to understand how different type of iterations work in Python

For example following line will go through every line of dataframe all of the data frames

portfolio_pnl = (
(aapl_position - aapl_position.shift()) 
+ (amzn_position - amzn_position.shift())
)

Yet in the following situation, one has to use apply to ensure that a function is applied to every line

s = pd.read_csv("stock.csv", squeeze = True)
#### adding 5 to each value
new = s.apply(lambda num : num + 5)

So my question is: Where and how would one know to use apply or any other loop and where would one can just need to use a formula and expect that to be applied on every line by itself.

Akhan99
  • 9
  • 3
  • Welcome to Stack Overflow. Please use [Minimal Reproducible Examples](https://stackoverflow.com/help/minimal-reproducible-example) instead of throwing around random code segments with unintelligible variable names. – SimonUnderwood May 13 '23 at 14:41
  • You add 5 to each value with `new = s + 5`. Use `apply` if you need to apply a more complicated function, not adding a constant –or a shifted datraframe, which is more or less like adding a constant. – Ignatius Reilly May 13 '23 at 15:28
  • Does this answer your question? [How to iterate over rows in a DataFrame in Pandas](https://stackoverflow.com/questions/16476924/how-to-iterate-over-rows-in-a-dataframe-in-pandas) – Ignatius Reilly May 13 '23 at 15:32
  • the conventional form of iterations (`for loop`) and a Dataframe which is vectorised are different... – D.L May 13 '23 at 17:37
  • Please note that this is not exactly a Python concept. This is a pandas and numpy concept. Those packages override the normal operators to operate on the entire array at once. If you do `[1,2,3] + [4,5,6]`, you'll get a very different answer (specifically, concatenation -- `[1,2,3,4,5,6]`). – Tim Roberts May 13 '23 at 23:40

0 Answers0