1Z3173C0D3
1Z3173C0D3

Reputation: 51

How to apply function to a dataframe passing a column as an argument

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?

Upvotes: 0

Views: 214

Answers (1)

Rutger
Rutger

Reputation: 603

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.

Upvotes: 1

Related Questions