Append a new row 'k' to df with your choice of values for each column. Then delete that row to return the original…
PythonLevel: Foundationpandas · DataFrame
Append a new row 'k' to df with your choice of values for each column. Then delete that row to return the original DataFrame.
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.loc['k'] = [5.5, 'dog', 'no', 2]
# and then deleting the new row...
df = df.drop('k')
Source and licence: 100 pandas puzzles — Alex Riley and contributors · MIT