Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to map integer to string value in pandas dataframe

I have this python dictionary:

dictionary = {
        '1':'A',
        '2':'B',
        '3':'C',
        '4':'D',
        '5':'E',
        '6':'F',
        '7':'G',
        '8':'H',
        '8':'I',
        '9':'J',
        '0':'L'
        }

The I have created this simple pandas dataframe:

import pandas as pd
ds = {'col1' : [12345,67890], 'col2' : [12364,78910]}

df = pd.DataFrame(data=ds)
print(df)

Which looks like this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    col1   col2
0  12345  12364
1  67890  78910

I would like to transform each and every digit in col1 (which is an int field) to the correspondent letter as per dictionary indicated above. So, basically I’d like the resulting dataframe to look like this:

    col1   col2 col1_transformed
0  12345  12364            ABCDE
1  67890  78910            FGHIJ

Is there a quick, pythonic way to do so by any chance?

>Solution :

Try:

df[df.columns + "_transformed"] = df.apply(
    lambda x: [
        "".join(dictionary.get(ch, "") for ch in s) for s in map(str, x)
    ],
    axis=1,
    result_type="expand",
)
print(df)

Prints:

    col1   col2 col1_transformed col2_transformed
0  12345  12364            ABCDE            ABCFD
1  67890  78910            FGIJL            GIJAL
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading