Search code examples
pythonpandaselementapplypython-applymap

Python: Apply function to certain elements/cells in pandas dataframe


I Have the following table in Pandas.

+--------+--------+--------+-----+
|   A    |   B    |   C    |  D  |
+--------+--------+--------+-----+
| foo    | b'bar0 | b'foo0 | 253 |
| b'bar0 | bar    | blah   | 485 |
+--------+--------+--------+-----+

I want to appy a function to each element in the cell that starts with b'. The function is:

def elementdecode(data,password):
    aa=row[2:-1]
    bb=aa.encode()
    cc = bb.decode('unicode-escape').encode('ISO-8859-1')
    return (decode(cc, password).decode())

Background: I have a csv file that has normal values and encrypted values in them, and I would like to apply the decryption method only on elements that are not encrypted. My plan is to read in the csv into pandas and apply the decryption function only on cells that are encrypted (e.g. start with 'b). Once the encryption has been performed I export the data back into a new csv. Rather than using loops I was thinking to use applymap, but I don't know how to do it only on specific elements.

Thanks


Solution

  • Have you tried that ?

    def elementdecode(data,password):
        #if the first condition if not met, the second is not evaluated
        if (type(x) == str) and ("\'b" in x):
            aa=row[2:-1]
            bb=aa.encode()
            cc = bb.decode('unicode-escape').encode('ISO-8859-1')
            return (decode(cc, password).decode())
        else:
            return x
    
    df.applymap(lambda x: elementdecode(x,password))