Joe_ft
Joe_ft

Reputation: 341

Python Function does not work

I have got the following df:

df = pd.DataFrame(columns=['mbs','Wholesale Data Usage'], index=['x','y','z'])
df.loc['x'] = pd.Series({'mbs':32, 'Wholesale Data Usage':36})
df.loc['y'] = pd.Series({'mbs':64, 'Wholesale Data Usage':62})
df.loc['z'] = pd.Series({'mbs':256, 'Wholesale Data Usage':277})

Moreover I have defined the following function:

def calculate_costs(row):
    mbs = row.loc['mbs']
    wdu = row.loc['Wholesale Data Usage']

    ac = 0
    if wdu >= mbs:
        if mbs == 32 | mbs == 64:
            ac = (wdu - mbs) * 0.05
        elif mbs == 128 | mbs == 256:
            ac = (wdu - mbs) * 0.036
        elif mbs == 512 | mbs == 1024:
            ac = (wdu - mbs) * 0.018

    return ac

For some reason if I apply the function to my df all of the row values are 0:

df['Additional Charge'] = df.apply(lambda r: calculate_costs(r), axis=1)

Could you please advise what I am doing wrong?

Upvotes: 0

Views: 55

Answers (1)

Bowen Kuang
Bowen Kuang

Reputation: 100

I am not sure if this is what you want, the result is not zero now. (I changed the | symbol to "or")

def calculate_costs(row):
    mbs = row.loc['mbs']
    wdu = row.loc['Wholesale Data Usage']
    print(mbs,wdu)
    ac = 0
    if wdu >= mbs:
        print("Hej")
        if mbs == 32 or mbs == 64:
            ac = (wdu - mbs) * 0.05
        elif mbs == 128 or mbs == 256:
            ac = (wdu - mbs) * 0.036
        elif mbs == 512 or mbs == 1024:
            ac = (wdu - mbs) * 0.018
        else:
            print ("Hello")
    return ac

Upvotes: 1

Related Questions