2

Trying to seek a value from a dataframe as the following:

df = pd.DataFrame({'Price': [2,4,6,7,8],
                   'compare': [True, True, False, False, True]})

If the value in 'compare' is True, I want to print the number that corresponds in the same row but in the 'Price' column, once I print this, I want to print the one row before it in column 'price' and one after in column 'price'

Any ideas? I thought of for looping through and then trying to get those values but I couldn't find a way to make it happen.

Any suggestions on a pd method or function that I can run and make get those values?

Yoav Poni
  • 95
  • 1
  • 12
  • it can be done fairly easy in Pandas and without loops. Please provide a small sample data set and your desired data set – MaxU - stand with Ukraine Aug 04 '17 at 17:46
  • For some reason I can't upload a picture. my end goal is to get to a math calculation provided by the numbers I get through iterating whether one column is true or not. and if this column a value in the column is true so the value in another column would be helpful for a calculation done seperatley – Yoav Poni Aug 04 '17 at 17:50
  • Please read [how to make good reproducible pandas examples](http://stackoverflow.com/questions/20109391/how-to-make-good-reproducible-pandas-examples) and edit your post correspondingly. – MaxU - stand with Ukraine Aug 04 '17 at 17:51

1 Answers1

3

IIUC:

In [42]: df.assign(prev_price=df.Price.shift(), next_price=df.Price.shift(-1))
Out[42]:
   Price  compare  next_price  prev_price
0      2     True         4.0         NaN
1      4     True         6.0         2.0
2      6    False         7.0         4.0
3      7    False         8.0         6.0
4      8     True         NaN         7.0

filtered:

In [43]: df.loc[df.compare].assign(prev_price=df.Price.shift(), next_price=df.Price.shift(-1))
Out[43]:
   Price  compare  next_price  prev_price
0      2     True         4.0         NaN
1      4     True         6.0         2.0
4      8     True         NaN         7.0
MaxU - stand with Ukraine
  • 205,989
  • 36
  • 386
  • 419