1

I have two dataframes the same size (3 by 3), one is Logical (True/False) and the other is numerical:

Logical df Numerical df

My script allows the user to input a specific coordinate from the Logical Matrix in order to change it from False to True (if it is already True, just ignores the command). After that, I want to apply the style.applymap function to color the elements in my numerical df corresponding to the True values.

style.applymap(func, subset=((row), [columns])

Thus, my approach was to save the indexes of the True values and add them to the subset using my numerical df. However, I cannot add my specific indexes on the subset field nor add more than one row in the subset parameter. So far, my code goes like this:

Occupato = pd.DataFrame(np.zeros(shape = (3, 3)))
for i in range(3):
    Occupato = Occupato.astype({i: bool})

normale = pd.DataFrame(np.random.randint(0,10,size=(3, 3)), columns=list('ABC')) 


def colore(v, colore):
    # if v:
        return f"background-color: {colore};" 

idx = ('Insert coordinates as [x, y]: ')
Occupato.iloc[idx[0], idx[1]]
normale.style.applymap(colore, colore='blue', subset = (row), [columns])

Now, I find it weird to see the syntax for the subset, using parenthesis () for rows -and only accepting one integer- whereas for columns, square brackets[] and allowing multiple values. Thanks in advance.

I tried:

mydf.style.applymap(colore, colore='blue', subset = (rows), [columns])

I expected to obtain the list elements specified on the subset and colored blue. Instead I obtained:

KeyError: "None of [Index([(1, 2)], dtype='object')] are in the [index]"

1 Answer 1

0

I would do it this way :

def colore(_, o, colore): #the white color is optional
    d_map = {True: f"background-color: {colore};color: white", False: ""}
    return o.replace(d_map)

normale.style.apply(colore, o=occupato, colore="blue", axis=None)

Output :

enter image description here

Inputs used :

print(occupato)

       A      B      C
0  False   True   True
1   True  False  False
2   True  False   True

print(normale)

    A  B  C
0   1  5  3
1   7  6  5
2  11  3  4
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks it worked. 100% The key was to add the .replace() function and changing applymap -> apply.

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.