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:
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?
Advertisement
Answer
You can assign to selected columns:
df.iloc[:, 1:] = df.iloc[:, 1:].applymap(ord)
Or:
df.loc[:, 1:] = df.loc[:, 1:].applymap(ord)