Reputation: 367
I have a dictionary of values:
Dict = {
"KeyA":"ValueA",
"KeyB":"ValueB",
"KeyC":"ValueC"
}
And I have a dataframe where the values in a column are lists:
index Column
0 ["KeyA", "KeyB"]
1 ["KeyB", "KeyC"]
2 ["KeyA", "KeyC"]
And I want returned:
index Column
0 ["ValueA", "ValueB"]
1 ["ValueB", "ValueC"]
2 ["ValueA", "ValueC"]
I have tried using the replace function:
df['Column'] = df['Column'].replace(Dict)
But this does not appear to work with lists.
Is there a simple way of replacing the list values with a dictionary?
Upvotes: 2
Views: 995
Reputation: 13878
Use apply
:
d = {
"KeyA":"ValueA",
"KeyB":"ValueB",
"KeyC":"ValueC"
}
df['Column'] = df['Column'].apply(lambda x: [d[i] for i in x])
Output:
Column
0 [ValueA, ValueB]
1 [ValueB, ValueC]
2 [ValueA, ValueC]
Also, naming your variables so similar to reserved names is bad karma.
Upvotes: 3