Reputation: 3899
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
Upvotes: 1
Views: 768
Reputation: 4903
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'])
Upvotes: 0
Reputation: 22503
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
Upvotes: 2