Given a DataFrame of random numeric values: how do you subtract the row mean from each element in the row? Assume…
PythonLevel: Intermediate
Given a DataFrame of random numeric values:
df = pd.DataFrame(np.random.random(size=(5, 3))) # this is a 5x3 DataFrame of float values
how do you subtract the row mean from each element in the row?
Assume import pandas as pd and import numpy as np.
Hints
- First define row granularity, column types and keys.
- Check index alignment, missing values and output size after the transformation.
Answer
df = pd.DataFrame(np.random.random(size=(5, 3)))
df.sub(df.mean(axis=1), axis=0)
Source and licence: 100 pandas puzzles — Alex Riley and contributors · MIT