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

Applymap on all but one Pandas DataFrame?

I have a DataFrame df that looks like this:

    0       1   2   3   4   5
0   first   M   A   F   I   L
1   second  M   A   F   I   L
2   third   M   S   F   I   I
3   fourth  M   S   F   I   L
4   fifth   M   L   F   F   I

I would like to change each element of each column except for the first to its corresponding integer ASCII code (i.e. "M" gets mapped to the integer 77, "A" gets mapped to 65, etc.).

I can achieve this result with the following:

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

new_df = df.loc[:, 1:].applymap(ord)
new_df.insert(0, 0, df[0])

Is there a better way to do this? There must be a better way to do this than by creating a new DataFrame. Perhaps a way to do applymap in-place on a subset of columns?

>Solution :

You can assign to selected columns:

df.iloc[:, 1:] = df.iloc[:, 1:].applymap(ord)

Or:

df.loc[:, 1:] = df.loc[:, 1:].applymap(ord)
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