1

I would like to encode the row values of the selected column in pandas.

For example, let's assume I have the following dataframe

    Col_A  Col_B
0    SV     NT
1    NT     P
2    SV     I
3    P      SV
4    I      P

I have a dictionary containing the encode values for each row of a column like below

encode_values = { 
    "Col_A" : {"NT": 1, "SV": 0, "P": 1, "I": 0},
    "Col_B": {"NT": 10, "SV": 0, "P": 10, "I": 0}
}

I want a new dataframe with the custom encodings for each of those columns

Result: -

    Col_A  Col_B
0    0     10
1    1     10
2    0     0
3    1     0
4    0     10

2 Answers 2

2

You can apply and map using column names:

print (df.apply(lambda d: d.map(encode_values[d.name])))

   Col_A  Col_B
0      0     10
1      1     10
2      0      0
3      1      0
4      0     10
Sign up to request clarification or add additional context in comments.

Comments

0

Try replace with dictionary as parameter, apply separately to each series in the df:

df.Col_A = df.Col_A.replace (encode_values['Col_A'])
df.Col_B = df.Col_B.replace (encode_values['Col_B'])

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.