The 'priority' column contains the values 'yes' and 'no'. Replace this column with a column of boolean values: 'yes'…
PythonLevel: Foundationpandas · DataFrame
The 'priority' column contains the values 'yes' and 'no'. Replace this column with a column of boolean values: 'yes' should be True and 'no' should be False.
Assume import pandas as pd and import numpy as np.
Starting data:
data = {'animal': ['cat', 'cat', 'snake', 'dog', 'dog', 'cat', 'snake', 'cat', 'dog', 'dog'],
'age': [2.5, 3, 0.5, np.nan, 5, 2, 4.5, np.nan, 7, 3],
'visits': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1],
'priority': ['yes', 'yes', 'no', 'yes', 'no', 'no', 'no', 'yes', 'no', 'no']}
labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
df = pd.DataFrame(data, index=labels)
Hints
- Distinguish a missing value from zero, an empty string and false.
- Test comparison, aggregation and filtering on a tiny missing-value example.
Answer
df['priority'] = df['priority'].map({'yes': True, 'no': False})
Source and licence: 100 pandas puzzles — Alex Riley and contributors · MIT