3

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:

    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?

2 Answers 2

3

A possible solution (notice that 8 is repeated in your dictionary -- a typo? -- and, therefore, my result does not match yours):

def f(x):
    return ''.join([dictionary[y] for y in str(x)])

df['col3'] = df['col1'].map(f)

Output:

    col1   col2   col3
0  12345  12364  ABCDE
1  67890  78910  FGIJL
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

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.