0

I have a dataframe

        df: 
        | A     | B |
    1   | "USA" | 2 |
    2   | "USA" |NAN|
    3   | "GER" | 3 |
    4   | "FRA" | 4 |

and a function which checks wether a value is in a certain bitmap if so returns true else returns false

import pandas as pd
import numpy as np
import os
def valInBitmap(reason, bitmap):
    if(pd.isna(bitmap)):
        return(False)
    if(reason == bitmap):
        return(True)
    n = 0
    while(bitmap>=0):
        if(bitmap<2**n):#4 < 2^3 <8 n= 3
            #print("bitmap:" +str(bitmap) +" < 2^n: 2^" +str(n)+" = "+str(n**2))
            if(reason == 2**(n-1)):#2 == 2^(3-1) = 4
                return(True)
                break
            bitmap = bitmap - 2**(n-1)          
            n = 0
        n  =n+1
    return(False)

Now I want to use the function on column "B" and return the outcome of each row to a new column "C"

df['C'] = df.apply(lambda row : valInBitmap(2,df['B']), axis = 1)

The final dataframe should look like this:

        df: 
        |   A   |  B  |   C   |
    1   | "USA" |  2  | True  |
    2   | "USA" |  NA | False |
    3   | "GER" |  3  | True  |
    4   | "FRA" |  4  | False |

However When executing the code I get the following errror message

Exception has occurred: ValueError
('The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().', 'occurred at index 1')

I have already read other threads regarding this error message but I could not fully understand and it and use the suggested solutions to sovle my issue. What do I do wrong?

1 Answer 1

1

You can use the apply function on a dataframe but also on an individual column. If you only need column B, you can use:

df['C'] = df['B'].apply(valInBitmap)

The function will receive the value from column B one by one and whatever the function returns will be saved as the value in C.

Sign up to request clarification or add additional context in comments.

2 Comments

ok so I would change the function so that it only requires 1 argument which is the column and the other argument is not passed at all?
Exactly! The 2 does not much, if you want you can just hard code it in the function. At some moment on your Python journey you will want to use the apply on an entire data frame so it's good you already got a little taste for that.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.