Okay, here is a cheatsheet for common pandas DataFrame manipulations (df). This focuses on the actions most frequently used during data analysis.
Pandas DataFrame Cheatsheet (df)
Remember to always import pandas: import pandas as pd
1. Basic Info & Inspection
- View top/bottom rows:
df.head(n): First n rows (default 5)
df.tail(n): Last n rows (default 5)
df.sample(n): Random n rows
- Get dimensions:
df.shape: Tuple of (rows, columns)
- Get column names:
df.columns: Index object of column names
- Get row index:
df.index: Index object of row labels
- Get data types of columns:
df.dtypes: Series of dtypes for each column
df.info(): Concise summary (index, dtypes, non-null values, memory usage)
- Get descriptive statistics:
df.describe(): Summary statistics (count, mean, std, min, max, quartiles) for numeric columns.
df.describe(include='all'): Include non-numeric columns.
- Count unique values in a column:
df['column_name'].value_counts(): Series with counts of unique values.
- Get unique values in a column:
df['column_name'].unique(): Numpy array of unique values.
- Count number of unique values:
df['column_name'].nunique(): Number of unique values (excluding NaN).
2. Selection (Indexing)
- Select a single column:
df['column_name']: Returns a Series
- Select multiple columns:
df[['col1', 'col2', ...]]: Returns a DataFrame
- Select by label (
.loc):
df.loc[row_label]
df.loc[[label1, label2]]: Multiple rows
df.loc[start_label : end_label]: Slice rows by label (inclusive)
df.loc[row_label, column_label]
df.loc[:, column_label]
df.loc[:, [col1, col2]]
df.loc[start_label : end_label, col_label]
- Select by integer position (
.iloc):
df.iloc[row_index]
df.iloc[[index1, index2]]: Multiple rows
df.iloc[start_index : end_index]: Slice rows by index (exclusive of end)
df.iloc[row_index, column_index]
df.iloc[:, column_index]
df.iloc[:, [index1, index2]]
df.iloc[start_index : end_index, col_index]
- Mixed Selection (use with caution, prefer
.loc or .iloc):
df[start:end]: Slice rows by integer position (like iloc for rows) if index is default, or label if index is not default and slice is labels.
3. Filtering (Boolean Indexing)
- Select rows based on condition:
df[df['column_name'] > value]
- Combine multiple conditions:
df[(df['col1'] > val1) & (df['col2'] < val2)] (AND)
df[(df['col1'] == val1) | (df['col2'] == val2)] (OR)
df[~(df['col'] > value)] (NOT)
- Note: Use
& for AND, | for OR, ~ for NOT. Parentheses around conditions are often necessary.
- Check for inclusion in a list:
df[df['column_name'].isin([val1, val2, ...])]
- Check for null/not null:
df[df['column_name'].isna()] (or .isnull())
df[df['column_name'].notna()] (or .notnull())
4. Handling Missing Data
- Identify missing values:
df.isna() / df.isnull(): Boolean DataFrame where True indicates NaN
df.isna().sum(): Count of NaNs per column
df.isna().sum().sum(): Total count of NaNs in the DataFrame
- Drop rows/columns with missing values:
df.dropna(): Drop rows with any NaN (returns new DataFrame)
df.dropna(axis=1): Drop columns with any NaN
df.dropna(how='all'): Drop rows/columns only if all values are NaN
df.dropna(thresh=n): Drop rows/columns that have fewer than n non-NaN values.
df.dropna(subset=['col1', 'col2']): Drop rows with NaN in specified columns.
- Fill missing values:
df.fillna(value): Fill with a specific value
df.fillna(df['col'].mean()): Fill with column mean
df.fillna(method='ffill') / df.fillna(method='pad'): Forward fill
df.fillna(method='bfill') / df.fillna(method='backfill'): Backward fill
- Note: Most manipulation methods return a new DataFrame by default. Use
inplace=True to modify the DataFrame directly (e.g., df.dropna(inplace=True)).
5. Adding/Removing Data
- Add a new column:
df['new_column'] = value (constant value)
df['new_column'] = df['existing_column'] * 2 (based on existing data)
df['new_column'] = [list_of_values] (list must have same length as DataFrame)
df['new_column'] = df.apply(func, axis=1) (based on row-wise computation)
- Drop columns:
df.drop(columns=['col1', 'col2', ...]) (returns new DataFrame)
df.drop('single_col', axis=1) (equivalent)
- Drop rows:
df.drop(index=[0, 2, 5, ...]) (drop by index/label, returns new DataFrame)
df.drop(df[df['col'] > value].index) (drop rows based on a condition)
6. Modifying Data
- Rename columns/index:
df.rename(columns={'old_name': 'new_name', ...})
df.rename(index={0: 'first_row', ...})
- Change data type:
df['column_name'] = df['column_name'].astype('new_dtype') (e.g., 'int', 'float', 'object', 'category', 'datetime64')
df.astype({'col1': 'dtype1', 'col2': 'dtype2'})
- Apply a function to a Series (column):
df['column'].apply(my_function)
df['column'].map(my_function) (element-wise, similar to apply for Series)
- Apply a function row-wise or column-wise:
df.apply(my_function, axis=0) (column-wise)
df.apply(my_function, axis=1) (row-wise)
- Apply a function element-wise across DataFrame:
df.applymap(my_function) (applies function to every cell, slightly deprecated, prefer vectorized or apply where possible)
- String Operations (on Series of strings):
df['str_col'].str.lower(): Convert to lowercase
df['str_col'].str.upper(): Convert to uppercase
df['str_col'].str.contains('pattern'): Check for substring
df['str_col'].str.replace('old', 'new'): Replace substring
df['str_col'].str.split(','): Split string into list
- Datetime Operations (on Series of datetimes):
- Ensure column is datetime:
df['date_col'] = pd.to_datetime(df['date_col'])
df['date_col'].dt.year, .month, .day, .hour, .minute, .second, .dayofweek, .day_name()
df['date_col'].dt.strftime('%Y-%m-%d'): Format date
7. Sorting
- Sort by values:
df.sort_values(by='column_name'): Ascending
df.sort_values(by='column_name', ascending=False): Descending
df.sort_values(by=['col1', 'col2']): Sort by multiple columns
df.sort_values(by=['col1', 'col2'], ascending=[True, False])
- Sort by index:
df.sort_index(): Ascending
df.sort_index(ascending=False): Descending
df.sort_index(axis=1): Sort columns
8. Grouping & Aggregation (groupby)
- Group by one column and aggregate:
df.groupby('group_col')['agg_col'].mean(): Mean of 'agg_col' for each group in 'group_col'
df.groupby('group_col')['agg_col'].sum()
df.groupby('group_col')['agg_col'].count() (counts non-NaN)
df.groupby('group_col')['agg_col'].nunique() (counts unique non-NaN)
df.groupby('group_col')['agg_col'].size() (counts rows, including NaNs)
df.groupby('group_col')['agg_col'].max() / .min() / .std() / .var()
- Group by multiple columns:
df.groupby(['group_col1', 'group_col2'])['agg_col'].mean()
- Aggregate multiple columns:
df.groupby('group_col')[['agg_col1', 'agg_col2']].sum()
- Aggregate using multiple functions:
df.groupby('group_col')['agg_col'].agg(['mean', 'sum', 'count'])
df.groupby('group_col').agg({'agg_col1': 'mean', 'agg_col2': 'sum'})
df.groupby('group_col').agg({'agg_col1': ['mean', 'std'], 'agg_col2': 'sum'})
- Get size of each group:
df.groupby('group_col').size()
- Iterate over groups:
for name, group_df in df.groupby('group_col'): ...
9. Combining DataFrames
- Concatenate: Stack DataFrames vertically or horizontally.
pd.concat([df1, df2]): Stack vertically (adds rows), aligns columns by default.
pd.concat([df1, df2], axis=1): Stack horizontally (adds columns), aligns rows by index.
pd.concat([df1, df2], ignore_index=True): Reset index after concatenating rows.
- Merge: Combine DataFrames based on common columns (like SQL joins).
pd.merge(df1, df2, on='key_column'): Inner merge on 'key_column'
pd.merge(df1, df2, on=['key1', 'key2']): Merge on multiple keys
pd.merge(df1, df2, how='left', on='key'): Left merge
pd.merge(df1, df2, how='right', on='key'): Right merge
pd.merge(df1, df2, how='outer', on='key'): Outer merge
pd.merge(df1, df2, how='inner', on='key'): Inner merge (default)
pd.merge(df1, df2, left_on='df1_key', right_on='df2_key'): Merge on different key names.
- Join: Combine DataFrames based on index (defaulting to left join).
df1.join(df2): Left join on index
df1.join(df2, how='outer'): Outer join on index
df1.join(other_df, on='key_column'): Join df1's 'key_column' with other_df's index.
10. Reshaping Data (Pivot, Melt)
- Pivot Table: Create a spreadsheet-style pivot table.
pd.pivot_table(df, values='value_col', index='row_col', columns='col_col', aggfunc='mean')
df.pivot_table(...) (Method version)
- Melt: Unpivot DataFrame from wide to long format.
pd.melt(df, id_vars=['id_col1'], value_vars=['col_to_melt1', 'col_to_melt2'], var_name='variable_name', value_name='value_name')
11. Basic Math & Statistics
- Most numpy functions work directly on DataFrames/Series (e.g.,
np.sqrt(df))
- Arithmetic operators (+, -, *, /, %) work element-wise.
- Comparison operators (>, <, ==, !=, >=, <=) work element-wise, return boolean DataFrame.
df.sum(): Sum of each column
df.mean(): Mean of each column
df.median(): Median of each column
df.min() / df.max(): Min/Max of each column
df.std() / df.var(): Standard deviation / Variance of each column
df.count(): Non-NaN count of each column
df.corr(): Correlation matrix
df.cov(): Covariance matrix
df.cumsum(): Cumulative sum
- Note: Add
axis=1 to perform operation row-wise instead of column-wise (e.g., df.sum(axis=1)).
Key Concepts & Tips:
- Immutability: Most operations return a new DataFrame. Use
inplace=True only when you intend to modify the original DataFrame directly (often discouraged in favor of assigning to a new variable).
- Vectorization: Prefer using built-in pandas methods (
.str, .dt, mathematical operators, .apply) over explicit Python loops for performance.
- Chaining: Many operations can be chained together for conciseness (e.g.,
df.dropna().groupby('col').mean()).
axis=0 vs axis=1: axis=0 refers to operations along index (rows, applying function column-wise); axis=1 refers to operations along columns (applying function row-wise).
- Getting Help: Use
help(df.method_name) or df.method_name? in an interactive environment (like Jupyter) to see documentation.
This covers the most common tasks for data manipulation and preparing your data for analysis! Good luck!