0

I have a variable initial_value, equal to 1000, that I would like to sum to values on Column B. initial_value and Column B will only be summed when Column C is equal to 1 and not 0. Therefore, the resulting initial value after the Class operation should be 1030 (or 1000 + 10 - 30 + 70 + 10). So far I have tried:

import pandas as pd
from __future__ import division
import numpy as np

    df = pd.DataFrame({"A":[40,50,60,70,20,30,40,10,10,80,60,40,50],\
 "B":[0,10,10,10,-50,10,10,-30,0,70,-20,-20,10], \
 "C":[0,0,0,1,0,0,0,1,0,1,0,0,1]})

A = df['A']
B = df['B']
C = df['C']

initial_value = 1000.00

class test:
    def __init__(self, A, B, C, initial_value):
        self.A = A
        self.B = B
        self.C = C
        self.initial_value = initial_value

    def test_values(self):
        self.initial_value = self.initial_value + self.B

        return self.initial_value

x = test(A, B, C, initial_value)
x.test_values()

print x

2 Answers 2

1

You can multiply column B and column C and then sum the result up:

def test_values(self):
    self.initial_value = self.initial_value + self.B.mul(self.C).sum()
                                            # ^^^^^^^^^^^^^^^^^^^^^^^^
    return self.initial_value
​​
x = test(A, B, C, initial_value)
x.test_values()
# 1060.0
Sign up to request clarification or add additional context in comments.

Comments

1

This will work:

def test_values(self):
    self.inital_value += sum(self.B*self.C)
    return self.initial_value

Just sum over the product of C and B:

import pandas as pd
from __future__ import division
import numpy as np

df = pd.DataFrame({"A":[40,50,60,70,20,30,40,10,10,80,60,40,50],\
"B":[0,10,10,10,-50,10,10,-30,0,70,-20,-20,10], \
"C":[0,0,0,1,0,0,0,1,0,1,0,0,1]})

A = df['A']
B = df['B']
C = df['C']

initial_value = 1000.00

class test:
    def __init__(self, A, B, C, initial_value):
        self.A = A
        self.B = B
        self.C = C
        self.initial_value = initial_value

    def test_values(self):
        self.inital_value += sum(self.B*self.C)
        return self.initial_value

x = test(A, B, C, initial_value)
print(x.test_values())

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.