Topics in this subject
Pandas 3 min read Updated 4 Aug 2026

Pandas Exercises

P1. Create a DataFrame from a dict. pd.DataFrame({'a':[1,2],'b':[3,4]})

P1. Create a DataFrame from a dict. pd.DataFrame({'a':[1,2],'b':[3,4]})

P2. Read a CSV. pd.read_csv('f.csv')

P3. Show first 5 rows and dtypes. df.head(); df.dtypes

P4. Select one column as a Series. df['col']

P5. Select rows where age > 30. df[df.age>30]

P6. Select rows with multiple conditions. df[(df.age>30)&(df.city=='NYC')]

P7. Get row by label / position. df.loc['x']; df.iloc[0]

P8. Count missing values per column. df.isna().sum()

P9. Fill NaN with column mean. df['c'].fillna(df['c'].mean())

P10. Drop rows with any NaN. df.dropna()

P11. Remove duplicate rows. df.drop_duplicates()

P12. Rename a column. df.rename(columns={'a':'A'})

P13. Add a computed column. df['ratio']=df.a/df.b

P14. Group by category, mean of value. df.groupby('c')['v'].mean()

P15. Named aggregation of two stats. df.groupby('c').agg(m=('v','mean'), n=('v','count'))

P16. Group-normalize a column with transform. df.groupby('c')['v'].transform(lambda s:(s-s.mean())/s.std())

P17. Merge two DataFrames on a key. pd.merge(l,r,on='id',how='left')

P18. Concatenate rows of two frames. pd.concat([a,b])

P19. Pivot a long table to wide. df.pivot_table(index='d',columns='c',values='v',aggfunc='sum')

P20. Melt wide to long. df.melt(id_vars='id')

P21. Sort by a column descending. df.sort_values('v',ascending=False)

P22. Top 3 by value. df.nlargest(3,'v')

P23. Value counts of a column. df['c'].value_counts()

P24. Unique count. df['c'].nunique()

P25. Convert a column to datetime. pd.to_datetime(df['d'])

P26. Extract month from a date column. df['d'].dt.month

P27. Resample daily to monthly sum. df.set_index('d')['v'].resample('M').sum()

P28. 7-day moving average. df['v'].rolling(7).mean()

P29. Filter strings containing 'abc'. df[df.s.str.contains('abc')]

P30. Split a string column into two. df['s'].str.split('-',expand=True)

P31. One-hot encode a categorical. pd.get_dummies(df,columns=['c'])

P32. Bin a numeric column into 3 groups. pd.qcut(df['v'],3)

P33. Compute % change of a column. df['v'].pct_change()

P34. Lag a column by 1. df['v'].shift(1)

P35. Cumulative sum within groups. df.groupby('c')['v'].cumsum()

P36. Get the row with max value per group. df.loc[df.groupby('c')['v'].idxmax()]

P37. Reduce memory: string → category. df['c']=df['c'].astype('category')

P38. Reset a MultiIndex. df.reset_index()

P39. Cross-tab two categoricals. pd.crosstab(df.a, df.b)

P40. Explode a list column. df.explode('items')