Archives Wild Code School
Python

Ternary Operators

Quête 61 sur 66

Salut :var[user.firstname] 👋 Alors, Pandas te plaît ?

Une fois qu'on commence à apprendre Pandas, on réalise que la Data Analysis (analyse de données) ne consiste pas à travailler sur une seule valeur, mais à analyser, manipuler et transformer tous les points de données du dataset (jeu de données) en même temps. En plus, on se rend compte qu'un code plus court est un code plus facile à lire. Et ça, du coup, ça fait moins d'erreurs. Qui n'aurait pas envie de googler moins souvent ?

Les Ternary Operators (opérateurs ternaires : une condition écrite sur une seule ligne) sont pratiques pour écrire du code plus court et gérer des manipulations complexes. Voyons comment.

Avant de commencer cette quête, va réviser les quêtes suivantes :

Quêtes liées

Contenu

À la fin de cette quête, tu seras capable de : ✅ reconnaître quand utiliser un Ternary Operator, ✅ l'utiliser avec aisance pour manipuler des DataFrames (tableaux de données à deux dimensions, comme un tableur)

Quand utiliser le Ternary Operator

Félicitations, tu travailles pour Netflix !! :tada::tada:

On t'a confié la tâche d'ajuster le dataset de films de façon à ce que l'équipe de développement mobile puisse reconnaître rapidement les films qui conviennent aux enfants. Il a été décidé que pour les films qui ne sont pas adaptés aux enfants, il y aura un point rouge à côté de l'image.

Comme tout bon Data Analyst (analyste de données), tu veux d'abord jeter un œil au dataset :

python
movies = pd.read_csv('https://raw.githubusercontent.com/justmarkham/pandas-videos/master/data/imdb_1000.csv')
movies.head()
hidden
Click to reveal|||text|||What's the name of the column with the content rating?
content_rating

Maintenant, vérifions les valeurs dans la colonne.

python
movies['content_rating'].unique()

La valeur utilisée quand le film est totalement adapté aux enfants est 'G'. On doit créer une colonne appelée 'safe_for_children'. La valeur est 'yes' quand le film est adapté aux enfants et a le content rating (classification du contenu) 'G', sinon la colonne 'safe_for_children' aura la valeur 'no'.

Bravo

Les Ternary Functions s'utilisent quand la valeur de la colonne dérivée dépend de la valeur de la colonne de départ.

Comment utiliser une Ternary Function

Dans les quêtes précédentes, on a déjà vu une méthode pour accomplir cette tâche.

hidden
Click to reveal|||python|||Can you write the code using a function and apply?
def check_safety(rating):
  safe_for_children = ''
  if rating == 'G':
    safe_for_children = 'yes'
  else:
    safe_for_children = 'no' 
  return safe_for_children

movies['safe_for_children'] = movies['content_rating'].apply(check_safety)
movies.head()

C'est un peu long, non ? Parmi les nombreuses façons de raccourcir le code, rien ne donne un code plus court que le Ternary Operator.

Le Ternary Operator donne le résultat de la condition sur une seule ligne. Regardons d'abord la structure du code :

python
# if structure
if condition_for_True:
    variable = value_for_True
else: 
    variable = value_for_False

# Ternary Operator structure
variable = value_for_True if condition_for_True else value_for_False

Maintenant, il nous suffit de l'utiliser à la place du code qu'on a écrit avant.

python
def check_safety(rating):
  safe_for_children = 'yes' if rating == 'G' else 'no'
  return safe_for_children

movies['safe_for_children'] = movies['content_rating'].apply(check_safety)
movies.head()

C'est déjà plus court qu'avant, et beaucoup plus clair ! On peut réduire encore le nombre de lignes en utilisant apply avec la fonction lambda :

python
movies['safe_for_children'] = movies['content_rating'].apply(lambda rating: 'yes' if rating == 'G' else 'no')
movies.head()

Une fois qu'on manipule le dataset, on remarque qu'il y a des films classés 'PG', 'GP' et 'PG-13'. Ce sont ceux qui sont indiqués comme pas vraiment adaptés aux enfants. On propose donc un changement : ajouter l'option 'parental supervision' pour les films qui ont le content rating 'PG', 'GP' et 'PG-13'.

Pour faire ça, il suffit d'utiliser la ternary function deux fois, l'une à la suite de l'autre.

python
movies['safe_for_children'] = movies['content_rating'].apply(lambda rating: 'yes' if rating == 'G' else 'parental_supervision' if 'G' in str(rating) else 'no')
movies.head()

On a ajouté str devant rating parce qu'il y a des NaN (valeurs manquantes) dont on ne s'est pas encore occupé. Si on voulait régler le problème des NaN en amont, qu'est-ce que tu ferais ?

Exemple supplémentaire

Notre collègue du User Design (conception de l'expérience utilisateur) est de retour. Il est content de notre travail et nous demande d'ajouter une information supplémentaire : savoir si le film est 'short-medium' (moins de 150 minutes) ou 'long' (dure plus de 150 minutes).

hidden
Click to reveal|||python|||How can we complete the task?
movies['type_duration'] = movies['duration'].apply(lambda minutes: 'short-medium' if minutes < 150 else 'long')
movies.head()

Ressources supplémentaires

↗
https://book.pythontips.com/en/latest/ternary_operators.html

Plus de théorie

book.pythontips.com
↗
https://www.geeksforgeeks.org/ternary-operator-in-python/

Exemples supplémentaires

geeksforgeeks.org
↗
https://www.youtube.com/watch?v=icIuzMYl728

Explication en vidéo

youtube.com

Challenge

Dans ce challenge, tu devras accomplir une nouvelle série de missions pour apprendre à répondre à des questions complexes sur tes données, en utilisant les ternary operators et apply lambda. Dans ce challenge, tu vas travailler sur le dataset goodreads, mais les compétences que tu apprends sont transférables à n'importe quel type de données tabulaires !

Crée une copie du notebook suivant et relève le challenge : Pandas - Ternary Operators

Ensuite, poste le lien de ton notebook Google Colaboratory comme solution, et pense à le partager avec les permissions en lecture.

Critères de validation

  • Le fichier lié peut être lu par toute personne ayant le lien

  • Toutes les missions ont été réalisées

Hello :var[user.firstname] 👋 How are you liking Pandas?

Once we start learning Pandas, we might start realizing how Data Analysis is not about the single value, but about analyzing, manipulating, and transforming all data point in the dataset at once. Moreover, we might start realizing that having shorter code makes for easier to read code. This in turn makes for less mistakes. Who wouldn't want to google less?

Ternary Operators are handy for shorter code and complex manipulation. Let's see how.

Before starting this quest, please go refresh the following quests:

Quêtes liées

Content

By the end of this quest, you'll be able to: ✅ recognize when to use a Ternary Operator, ✅ proficiently use it to manipulate DataFrames

When to use the Ternary Operator

Congratulation, you are working for Netflix!! :tada::tada:

You have been given the task to adjust the movie dataset in a way that the mobile development team can quickly recognize the movies that are ok for children to watch. It has been decided that for the kind of movies that are not good for children there will be a red dot next to the image.

As any great Data Analyst, you want to have a look at the dataset first:

python
movies = pd.read_csv('https://raw.githubusercontent.com/justmarkham/pandas-videos/master/data/imdb_1000.csv')
movies.head()
hidden
Click to reveal|||text|||What's the name of the column with the content rating?
content_rating

Now let's check the values in the column.

python
movies['content_rating'].unique()

The value that is used when the movie is completely safe for children is 'G'. We need to create a column called 'safe_for_children'. The value is 'yes' when the movie is safe for children and has the content rating 'G', otherwise the 'safe_for_children' column will have the value 'no'.

Bravo

Ternary Functions are to be used when the value in the derived column depends on the value in the initial column.

How to use a Ternary Function

In the previous quests we already covered a method to complete this task.

hidden
Click to reveal|||python|||Can you write the code using a function and apply?
def check_safety(rating):
  safe_for_children = ''
  if rating == 'G':
    safe_for_children = 'yes'
  else:
    safe_for_children = 'no' 
  return safe_for_children

movies['safe_for_children'] = movies['content_rating'].apply(check_safety)
movies.head()

It's a bit long, doesn't it? Of the many ways to shorten the code that we have, nothing gets a shorter code than the Ternary Operator.

The Ternary Operator gives the result of the condition in one line. Let's check the structure of the code first:

python
# if structure
if condition_for_True:
    variable = value_for_True
else: 
    variable = value_for_False

# Ternary Operator structure
variable = value_for_True if condition_for_True else value_for_False

Now we just need to use it instead of the code we wrote before.

python
def check_safety(rating):
  safe_for_children = 'yes' if rating == 'G' else 'no'
  return safe_for_children

movies['safe_for_children'] = movies['content_rating'].apply(check_safety)
movies.head()

This is already shorter than before, and much more clear! We can further reduce the lines by using apply with the lambda function:

python
movies['safe_for_children'] = movies['content_rating'].apply(lambda rating: 'yes' if rating == 'G' else 'no')
movies.head()

Once we manipulate the dataset, we notice that there are movies rated 'PG', 'GP', and 'PG-13'. Those that are suggested as not good for children. So we propose a change: add the 'parental supervision' option for movies that have the content rating 'PG', 'GP', and 'PG-13'.

In order to do this, we just need to use the ternary function twice, one time after the other.

python
movies['safe_for_children'] = movies['content_rating'].apply(lambda rating: 'yes' if rating == 'G' else 'parental_supervision' if 'G' in str(rating) else 'no')
movies.head()

We added str before rating because there are some NaN we didn't take care of yet. If we were to want to solve the NaNs problem beforehand, what would you do?

Additional Example

Our colleague from User Design is back. They are happy with our work and ask us to add an additional piece of information: whether the movie is 'short-medium'(less than 150 minutes), or 'long'(lasts more than 150 minutes).

hidden
Click to reveal|||python|||How can we complete the task?
movies['type_duration'] = movies['duration'].apply(lambda minutes: 'short-medium' if minutes < 150 else 'long')
movies.head()

Additional Resources

↗
https://book.pythontips.com/en/latest/ternary_operators.html

More theory

book.pythontips.com
↗
https://www.geeksforgeeks.org/ternary-operator-in-python/

Additional examples

geeksforgeeks.org
↗
https://www.youtube.com/watch?v=icIuzMYl728

Video explaination

youtube.com

Challenge

In this challenge, you will have to complete a new series of missions to learn how to answer complex questions about your data, using ternary operators and apply lambda. In this challenge, you will look at the goodreads dataset, but the skills you learn are transferable to any kind of tabular data!

Create a copy of the following notebook and take on the challenge: Pandas - Ternary Operators

Then post the link to your Google Colaboratory notebook as a solution please share it with read permissions.

Validation Criteria

  • The linked file can be read by anyone with the link

  • All the missions were carried out