Mixed NumPy + Pandas Exercises
M1. Convert a DataFrame column to a NumPy array. df['v'].tonumpy()
M1. Convert a DataFrame column to a NumPy array. df['v'].to_numpy()
M2. Apply a NumPy function to a column. np.log1p(df['v'])
M3. Add a column that is the row-wise max of two columns.
df['mx']=np.maximum(df.a, df.b)
M4. Standardize all numeric columns.
df=(df-df.mean())/df.std()
M5. Flag outliers beyond 3 std.
(np.abs((df.v-df.v.mean())/df.v.std())>3)
M6. Create a DataFrame from a NumPy 2-D array.
pd.DataFrame(np.arange(6).reshape(2,3), columns=list('abc'))
M7. Compute a correlation matrix. df.corr()
M8. Replace values conditionally with np.where.
df['g']=np.where(df.v>0,'pos','neg')
M9. Bucket with np.select (multi-condition).
df['t']=np.select([df.v<0, df.v==0],['neg','zero'],default='pos')
M10. Compute a weighted average.
np.average(df.v, weights=df.w)
M11. Fill NaN with group median (transform).
df['v']=df.groupby('g')['v'].transform(lambda s:s.fillna(s.median()))
M12. Vectorized distance from a target point.
np.sqrt((df.x-0)**2 + (df.y-0)**2)
M13. Percentile rank of each row.
df['v'].rank(pct=True)
M14. Convert wide numeric block to normalized rows.
arr=df.to_numpy(); arr/arr.sum(1, keepdims=True)
M15. Random train/test split.
msk=np.random.default_rng(0).random(len(df))<0.8; train,test=df[msk],df[~msk]