OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

Sum of columns based on range of values of other columns in a Pandas dataframe

  • Thread starter Thread starter AmirX
  • Start date Start date
A

AmirX

Guest
This is my dataframe:

Code:
df = pd.DataFrame({'sym': ['a', 'b'], 'vol_1': [100, 50], 'price_1': [5, 150], 'vol_2': [1500, 2000], 'price_2': [20, 175],
                   'vol_3': [123, 500], 'price_3': [22, 1000], 'min': [18, 150], 'max': [23, 176]})

I want to add a column that sums vol_1, vol_2, and vol_3 for each row if the price that is in the next column for each vol is in range of min and max cols. For example for the first row I want vol_2 and vol_3 because the prices are in range of min and max. My desired outcome looks like this:

Code:
 sym  vol_1  price_1  vol_2  price_2  vol_3  price_3  min  max  vol_sum
0   a    100        5   1500       20    123       22   18   23     1623
1   b     50      150   2000      175    500     1000  150  176     2050
<p>This is my dataframe:</p>
<pre><code>df = pd.DataFrame({'sym': ['a', 'b'], 'vol_1': [100, 50], 'price_1': [5, 150], 'vol_2': [1500, 2000], 'price_2': [20, 175],
'vol_3': [123, 500], 'price_3': [22, 1000], 'min': [18, 150], 'max': [23, 176]})
</code></pre>
<p>I want to add a column that sums <code>vol_1</code>, <code>vol_2</code>, and <code>vol_3</code> for each row if the price that is in the next column for each vol is in range of <code>min</code> and <code>max</code> cols.
For example for the first row I want <code>vol_2</code> and <code>vol_3</code> because the prices are in range of <code>min</code> and <code>max</code>.
My desired outcome looks like this:</p>
<pre><code> sym vol_1 price_1 vol_2 price_2 vol_3 price_3 min max vol_sum
0 a 100 5 1500 20 123 22 18 23 1623
1 b 50 150 2000 175 500 1000 150 176 2050
</code></pre>
 
Top