You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
# Bin a continuous column into labeled rangesdf['gpa_band'] =pd.cut(
df['gpa'],
bins=[0, 2.0, 3.0, 3.5, 4.0],
labels=['At Risk', 'Satisfactory', 'Good', 'Honors']
)
# Equal-sized quantile binsdf['gpa_quartile'] =pd.qcut(df['gpa'], q=4, labels=['Q1','Q2','Q3','Q4'])
6. Map Values to New Column — .map()
# Map from a dictionarymajor_dept= {'CS': 'Engineering', 'Math': 'Sciences', 'Physics': 'Sciences'}
df['department'] =df['major'].map(major_dept)
# Map Y/N to readable labelsdf['citizen_label'] =df['us_citizen'].map({'Y': 'Citizen', 'N': 'Non-Citizen'})
7. Group-Level Stats as a New Column — transform()
# Add group mean back to each row (no collapsing)df['major_avg_gpa'] =df.groupby('major')['gpa'].transform('mean')
df['major_max_gpa'] =df.groupby('major')['gpa'].transform('max')
df['major_headcount'] =df.groupby('major')['gpa'].transform('count')
# Flag students above their major's averagedf['above_major_avg'] =df['gpa'] >df['major_avg_gpa']
Result:
name
major
gpa
major_avg_gpa
above_major_avg
Alice
CS
3.9
3.70
True
Bob
Math
2.8
2.80
False
Carol
CS
3.5
3.70
False
8. Rank Column
# Rank all students by GPA (1 = highest)df['gpa_rank'] =df['gpa'].rank(ascending=False, method='dense').astype(int)
# Rank within each majordf['rank_in_major'] =df.groupby('major')['gpa'].rank(
ascending=False, method='dense'
).astype(int)
9. Rolling / Cumulative Columns
# Cumulative sum of credits (sorted first)df=df.sort_values('student_id')
df['cumulative_credits'] =df['credits'].cumsum()
# Rolling average (window of 2)df['rolling_avg_gpa'] =df['gpa'].rolling(window=2).mean()
10. Multiple New Columns with assign() — chainable
# assign() returns a new df — great for method chainingdf=df.assign(
full_name=df['first_name'] +' '+df['last_name'],
gpa_10pt=df['gpa'] *2.5,
is_citizen=df['us_citizen'] =='Y',
credits_left=120-df['credits']
)
# Keep columns by exact name listdf.filter(items=['student_id', 'gpa', 'major'])
# Keep columns whose names contain a substringdf.filter(like='name') # matches first_name, last_name, full_name# Keep columns matching a regexdf.filter(regex='^gpa') # matches gpa, gpa_10pt, gpa_rank
13. Drop Unwanted Columns — drop()
# Drop one columndf.drop(columns=['label'])
# Drop multiple columnsdf.drop(columns=['label', 'gpa_per_credit', 'rolling_avg_gpa'])
# Drop in placedf.drop(columns=['label'], inplace=True)
14. Select by Data Type — select_dtypes()
# Keep only numeric columnsdf.select_dtypes(include='number')
# Keep only string/object columnsdf.select_dtypes(include='object')
# Keep numeric + booldf.select_dtypes(include=['number', 'bool'])
# Exclude a typedf.select_dtypes(exclude='object')
15. Select Columns by Position — .iloc[]
df.iloc[:, 0] # first column onlydf.iloc[:, 0:3] # first 3 columnsdf.iloc[:, -2:] # last 2 columnsdf.iloc[:, [0,2,4]] # columns at index 0, 2, 4
16. Reorder Columns
# Define the exact order you wantcols= ['student_id', 'full_name', 'major', 'gpa', 'standing', 'credits']
df=df[cols]
# Move one column to the frontfirst_col='student_id'df=df[[first_col] + [cforcindf.columnsifc!=first_col]]
# Move one column to the endlast_col='credits'df=df[[cforcindf.columnsifc!=last_col] + [last_col]]