How can I map the conditions in lambda like the code below:
map(lambda example: {'labels': 1 if example['sentiment'] == 'positive',
2 if example['sentiment'] == 'negative'
else 0}
My dataset is:
sentiment
positive
negative
neutral
OBS: I know I can use get_dummies
but I need to do this with map lambda, please.
CodePudding user response:
This is not a good approach, but if you want the code this should work
map(lambda example: {'labels': 1 if example['sentiment'] == 'positive' else
(2 if example['sentiment'] == 'negative' else 0)}
CodePudding user response:
Whenever you have a bunch of simple if
/else
, it is almost always an hint that you should use a dict
:
>>> labels_mapping = {"positive": 1, "negative": 2, "neutral": 0}
>>> data = ["positive", "negative", "neutral", "positive"]
>>> data_labels = list(map(lambda example: labels_mapping[example], data))
>>> data_labels
[1, 2, 0, 1]
Actually, you then didn't need a lambda anymore, because you can use the __getitem__
method of the constructed dict
:
>>> list(map(labels_mapping.__getitem__, data))
[1, 2, 0, 1]
And to catch unexpected values (similar to the last else
clause of the corresponding if
/else
statement), you can use a defaultdict
to assign a default value:
>>> from collections import defaultdict
>>> labels_mapping = defaultdict(lambda: -1, {"positive": 1, "negative": 2, "neutral": 0})
>>> data = ["positive", "negative", "neutral", "positive", "noise"]
>>> data_labels = list(map(labels_mapping.__getitem__, data))
>>> data_labels
[1, 2, 0, 1, -1]