{"data":{"slug":"github-aipoch-medical-research-skills-scientific-skills-data-analysis-data-transform-6910d40c2111","title":"Data Transformation for Medical Research","summary":"Transform, clean, reshape, and preprocess data using pandas and numpy. Works with any LLM provider including GPT, Gemini, and Claude. The deliverable is a cleaned and processed dataset ready for analysis.","url":"https:\/\/skillshunter.net\/skills\/github-aipoch-medical-research-skills-scientific-skills-data-analysis-data-transform-6910d40c2111","json_url":"https:\/\/skillshunter.net\/api\/public\/v1\/skills\/github-aipoch-medical-research-skills-scientific-skills-data-analysis-data-transform-6910d40c2111","markdown_url":"https:\/\/skillshunter.net\/skills\/github-aipoch-medical-research-skills-scientific-skills-data-analysis-data-transform-6910d40c2111.md","download_url":"https:\/\/skillshunter.net\/skills\/github-aipoch-medical-research-skills-scientific-skills-data-analysis-data-transform-6910d40c2111\/download","category":{"slug":"data-research","name":"Data & Research"},"editor_note":"Ensure pandas, numpy, and sklearn are installed in your environment before running the workflow. The skill requires a local Python environment and a dataset file (e.g., 'data.csv') to operate.","instructions":"---\nname: data-transform\ndescription: Transform, clean, reshape, and preprocess data using pandas and numpy. Works with ANY LLM provider (GPT, Gemini, Claude, etc.).\nlicense: MIT\nauthor: AIPOCH\n---\n> **Source**: [https:\/\/github.com\/aipoch\/medical-research-skills](https:\/\/github.com\/aipoch\/medical-research-skills)\n\n\n# Data Transformation (Universal)\n\n## Overview\nThis skill enables you to perform comprehensive data transformations including cleaning, normalization, reshaping, filtering, and feature engineering. Unlike cloud-hosted solutions, this skill uses standard Python data manipulation libraries (**pandas**, **numpy**, **sklearn**) and executes **locally** in your environment, making it compatible with **ALL LLM providers** including GPT, Gemini, Claude, DeepSeek, and Qwen.\n\n## When to Use This Skill\n- Clean and preprocess raw data\n- Normalize or scale numeric features\n- Reshape data between wide and long formats\n- Handle missing values\n- Filter and subset datasets\n- Merge multiple datasets\n- Create new features from existing ones\n- Convert data types and formats\n\n## How to Use\n\n### Step 1: Import Required Libraries\n```python\nimport pandas as pd\nimport numpy as np\nfrom sklearn.preprocessing import StandardScaler, MinMaxScaler, RobustScaler\nfrom sklearn.preprocessing import LabelEncoder, OneHotEncoder\nimport warnings\nwarnings.filterwarnings('ignore')\n```\n\n### Step 2: Data Cleaning\n```python\n# Load data\ndf = pd.read_csv('data.csv')\n\n# Check for missing values\nprint(\"Missing values per column:\")\nprint(df.isnull().sum())\n\n# Remove duplicates\ndf_clean = df.drop_duplicates()\nprint(f\"Removed {len(df) - len(df_clean)} duplicate rows\")\n\n# Remove rows with any missing values\ndf_clean = df_clean.dropna()\n\n# Or fill missing values\ndf_clean = df.copy()\ndf_clean['numeric_col'] = df_clean['numeric_col'].fillna(df_clean['numeric_col'].median())\ndf_clean['categorical_col'] = df_clean['categorical_col'].fillna('Unknown')\n\n# Remove outliers using IQR method\ndef remove_outliers(df, column, multiplier=1.5):\n    Q1 = df[column].quantile(0.25)\n    Q3 = df[column].quantile(0.75)\n    IQR = Q3 - Q1\n    lower_bound = Q1 - multiplier * IQR\n    upper_bound = Q3 + multiplier * IQR\n    return df[(df[column] >= lower_bound) & (df[column] <= upper_bound)]\n\ndf_clean = remove_outliers(df_clean, 'expression_level')\nprint(f\"\u2705 Data cleaned: {len(df_clean)} rows remaining\")\n```\n\n### Step 3: Normalization and Scaling\n```python\n# Select numeric columns\nnumeric_cols = df.select_dtypes(include=[np.number]).columns\n\n# Method 1: Z-score normalization (StandardScaler)\nscaler = StandardScaler()\ndf_normalized = df.copy()\ndf_normalized[numeric_cols] = scaler.fit_transform(df[numeric_cols])\n\nprint(\"Z-score normalized (mean=0, std=1)\")\nprint(df_normalized[numeric_cols].describe())\n\n# Method 2: Min-Max scaling (0-1 range)\nscaler_minmax = MinMaxScaler()\ndf_scaled = df.copy()\ndf_scaled[numeric_cols] = scaler_minmax.fit_transform(df[numeric_cols])\n\nprint(\"\\nMin-Max scaled (range 0-1)\")\nprint(df_scaled[numeric_cols].describe())\n\n# Method 3: Robust scaling (resistant to outliers)\nscaler_robust = RobustScaler()\ndf_robust = df.copy()\ndf_robust[numeric_cols] = scaler_robust.fit_transform(df[numeric_cols])\n\nprint(\"\\nRobust scaled (median=0, IQR=1)\")\nprint(df_robust[numeric_cols].describe())\n\n# Method 4: Log transformation\ndf_log = df.copy()\ndf_log['log_expression'] = np.log1p(df_log['expression'])  # log1p(x) = log(1+x)\n\nprint(\"\u2705 Data normalized and scaled\")\n```\n\n### Step 4: Data Reshaping\n```python\n# Convert wide format to long format (melt)\n# Wide format: columns are different conditions\/samples\n# Long format: one column for variable, one for value\n\ndf_wide = pd.DataFrame({\n    'gene': ['GENE1', 'GENE2', 'GENE3'],\n    'sample_A': [10, 20, 15],\n    'sample_B': [12, 18, 14],\n    'sample_C': [11, 22, 16]\n})\n\ndf_long = df_wide.melt(\n    id_vars=['gene'],\n    var_name='sample',\n    value_name='expression'\n)\n\nprint(\"Long format:\")\nprint(df_long)\n\n# Convert long format to wide format (pivot)\ndf_wide_reconstructed = df_long.pivot(\n    index='gene',\n    columns='sample',\n    values='expression'\n)\n\nprint(\"\\nWide format (reconstructed):\")\nprint(df_wide_reconstructed)\n\n# Pivot table with aggregation\ndf_pivot = df_long.pivot_table(\n    index='gene',\n    columns='sample',\n    values='expression',\n    aggfunc='mean'  # Can use sum, median, etc.\n)\n\nprint(\"\u2705 Data reshaped\")\n```\n\n### Step 5: Filtering and Subsetting\n```python\n# Filter rows by condition\nhigh_expression = df[df['expression'] > 100]\n\n# Multiple conditions (AND)\nfiltered = df[(df['expression'] > 50) & (df['qvalue'] < 0.05)]\n\n# Multiple conditions (OR)\nfiltered = df[(df['celltype'] == 'T cell') | (df['celltype'] == 'B cell')]\n\n# Filter by list of values\nselected_genes = ['GENE1', 'GENE2', 'GENE3']\nfiltered = df[df['gene'].isin(selected_genes)]\n\n# Filter by string pattern\nfiltered = df[df['gene'].str.startswith('MT-')]  # Mitochondrial genes\n\n# Select specific columns\nselected_cols = df[['gene', 'log2FC', 'pvalue', 'qvalue']]\n\n# Select columns by pattern\nnumeric_cols = df.select_dtypes(include=[np.number])\ncategorical_cols = df.select_dtypes(include=['object', 'category'])\n\n# Sample random rows\ndf_sample = df.sample(n=1000, random_state=42)  # 1000 random rows\ndf_sample_frac = df.sample(frac=0.1, random_state=42)  # 10% of rows\n\n# Top N rows\ntop_genes = df.nlargest(10, 'expression')\nbottom_genes = df.nsmallest(10, 'pvalue')\n\nprint(f\"\u2705 Filtered dataset: {len(filtered)} rows\")\n```\n\n### Step 6: Merging and Joining Datasets\n```python\n# Inner join (only matching rows)\nmerged = pd.merge(df1, df2, on='gene', how='inner')\n\n# Left join (all rows from df1)\nmerged = pd.merge(df1, df2, on='gene', how='left')\n\n# Outer join (all rows from both)\nmerged = pd.merge(df1, df2, on='gene', how='outer')\n\n# Join on multiple columns\nmerged = pd.merge(df1, df2, on=['gene', 'sample'], how='inner')\n\n# Join on different column names\nmerged = pd.merge(\n    df1, df2,\n    left_on='gene_name',\n    right_on='gene_id',\n    how='inner'\n)\n\n# Concatenate vertically (stack DataFrames)\ncombined = pd.concat([df1, df2], axis=0, ignore_index=True)\n\n# Concatenate horizontally (side-by-side)\ncombined = pd.concat([df1, df2], axis=1)\n\nprint(f\"\u2705 Merged datasets: {len(merged)} rows\")\n```\n\n## Advanced Features\n\n### Handling Missing Values\n```python\n# Check missing value patterns\nmissing_summary = pd.DataFrame({\n    'column': df.columns,\n    'missing_count': df.isnull().sum(),\n    'missing_percent': (df.isnull().sum() \/ len(df) * 100).round(2)\n})\n\nprint(\"Missing value summary:\")\nprint(missing_summary[missing_summary['missing_count'] > 0])\n\n# Strategy 1: Fill with statistical measures\ndf_filled = df.copy()\ndf_filled['numeric_col'].fillna(df_filled['numeric_col'].median(), inplace=True)\ndf_filled['categorical_col'].fillna(df_filled['categorical_col'].mode()[0], inplace=True)\n\n# Strategy 2: Forward fill (use previous value)\ndf_filled = df.fillna(method='ffill')\n\n# Strategy 3: Interpolation (for time-series)\ndf_filled = df.copy()\ndf_filled['expression'] = df_filled['expression'].interpolate(method='linear')\n\n# Strategy 4: Drop columns with too many missing values\nthreshold = 0.5  # Drop if >50% missing\ndf_cleaned = df.dropna(thresh=len(df) * threshold, axis=1)\n\nprint(\"\u2705 Missing values handled\")\n```\n\n### Feature Engineering\n```python\n# Create new features from existing ones\n\n# 1. Binning continuous variables\ndf['expression_category'] = pd.cut(\n    df['expression'],\n    bins=[0, 10, 50, 100, np.inf],\n    labels=['Very Low', 'Low', 'Medium', 'High']\n)\n\n# 2. Create ratio features\ndf['gene_to_umi_ratio'] = df['n_genes'] \/ df['n_counts']\n\n# 3. Create interaction features\ndf['interaction'] = df['feature1'] * df['feature2']\n\n# 4. Extract datetime features\ndf['date'] = pd.to_datetime(df['timestamp'])\ndf['year'] = df['date'].dt.year\ndf['month'] = df['date'].dt.month\ndf['day_of_week'] = df['date'].dt.dayofweek\n\n# 5. One-hot encoding for categorical variables\ndf_encoded = pd.get_dummies(df, columns=['celltype', 'condition'], prefix=['cell', 'cond'])\n\n# 6. Label encoding (ordinal)\nle = LabelEncoder()\ndf['celltype_encoded'] = le.fit_transform(df['celltype'])\n\n# 7. Create polynomial features\ndf['expression_squared'] = df['expression'] ** 2\ndf['expression_cubed'] = df['expression'] ** 3\n\n# 8. Create lag features (time-series)\ndf['expression_lag1'] = df.groupby('gene')['expression'].shift(1)\ndf['expression_lag2'] = df.groupby('gene')['expression'].shift(2)\n\nprint(\"\u2705 New features created\")\n```\n\n### Grouping and Aggregation\n```python\n# Group by single column and aggregate\ncluster_stats = df.groupby('cluster').agg({\n    'expression': ['mean', 'median', 'std', 'count'],\n    'n_genes': 'mean',\n    'n_counts': 'sum'\n})\n\nprint(\"Cluster statistics:\")\nprint(cluster_stats)\n\n# Group by multiple columns\nstats = df.groupby(['cluster', 'celltype']).agg({\n    'expression': 'mean',\n    'qvalue': lambda x: (x < 0.05).sum()  # Count significant\n})\n\n# Apply custom function\ndef custom_stats(group):\n    return pd.Series({\n        'mean_expr': group['expression'].mean(),\n        'cv': group['expression'].std() \/ group['expression'].mean(),  # Coefficient of variation\n        'n_cells': len(group)\n    })\n\ncluster_custom = df.groupby('cluster').apply(custom_stats)\n\nprint(\"\u2705 Data aggregated\")\n```\n\n### Data Type Conversions\n```python\n# Convert column to different type\ndf['cluster'] = df['cluster'].astype(str)\ndf['expression'] = df['expression'].astype(float)\ndf['significant'] = df['significant'].astype(bool)\n\n# Convert to categorical (saves memory)\ndf['celltype'] = df['celltype'].astype('category')\n\n# Parse dates\ndf['date'] = pd.to_datetime(df['date_string'], format='%Y-%m-%d')\n\n# Convert numeric to categorical\ndf['expression_level'] = pd.cut(df['expression'], bins=3, labels=['Low', 'Medium', 'High'])\n\n# String operations\ndf['gene_upper'] = df['gene'].str.upper()\ndf['is_mitochondrial'] = df['gene'].str.startswith('MT-')\n\nprint(\"\u2705 Data types converted\")\n```\n\n## Common Use Cases\n\n### AnnData to DataFrame Conversion\n```python\n# Convert AnnData .obs (cell metadata) to DataFrame\ndf_cells = adata.obs.copy()\n\n# Convert .var (gene metadata) to DataFrame\ndf_genes = adata.var.copy()\n\n# Extract expression matrix to DataFrame\n# Warning: This can be memory-intensive for large datasets\ndf_expression = pd.DataFrame(\n    adata.X.toarray() if hasattr(adata.X, 'toarray') else adata.X,\n    index=adata.obs_names,\n    columns=adata.var_names\n)\n\n# Extract specific layer\nif 'normalized' in adata.layers:\n    df_normalized = pd.DataFrame(\n        adata.layers['normalized'],\n        index=adata.obs_names,\n        columns=adata.var_names\n    )\n\nprint(\"\u2705 AnnData converted to DataFrames\")\n```\n\n### Gene Expression Matrix Transformation\n```python\n# Transpose: genes as rows, cells as columns \u2192 cells as rows, genes as columns\ndf_transposed = df.T\n\n# Log-transform gene expression\ndf_log = np.log1p(df)  # log1p(x) = log(1+x), avoids log(0)\n\n# Z-score normalize per gene (across cells)\ndf_zscore = df.apply(lambda x: (x - x.mean()) \/ x.std(), axis=1)\n\n# Scale per cell (divide by library size)\nlibrary_sizes = df.sum(axis=1)\ndf_normalized = df.div(library_sizes, axis=0) * 1e6  # CPM normalization\n\n# Filter low-expressed genes\nmin_cells = 10  # Gene must be expressed in at least 10 cells\ngene_mask = (df > 0).sum(axis=0) >= min_cells\ndf_filtered = df.loc[:, gene_mask]\n\nprint(f\"\u2705 Filtered to {df_filtered.shape[1]} genes\")\n```\n\n### Differential Expression Results Processing\n```python\n# Assuming deg_df has columns: gene, log2FC, pvalue, qvalue\n\n# Add significance labels\ndeg_df['regulation'] = 'Not Significant'\ndeg_df.loc[(deg_df['log2FC'] > 1) & (deg_df['qvalue'] < 0.05), 'regulation'] = 'Up-regulated'\ndeg_df.loc[(deg_df['log2FC'] < -1) & (deg_df['qvalue'] < 0.05), 'regulation'] = 'Down-regulated'\n\n# Sort by significance\ndeg_df_sorted = deg_df.sort_values('qvalue')\n\n# Top upregulated genes\ntop_up = deg_df[deg_df['regulation'] == 'Up-regulated'].nlargest(20, 'log2FC')\n\n# Top downregulated genes\ntop_down = deg_df[deg_df['regulation'] == 'Down-regulated'].nsmallest(20, 'log2FC')\n\n# Create summary table\nsummary = deg_df.groupby('regulation').agg({\n    'gene': 'count',\n    'log2FC': ['mean', 'median'],\n    'qvalue': 'min'\n})\n\nprint(\"DEG Summary:\")\nprint(summary)\n\n# Export results\ndeg_df_sorted.to_csv('deg_results_processed.csv', index=False)\nprint(\"\u2705 DEG results processed and saved\")\n```\n\n### Batch Processing Multiple Files\n```python\nimport glob\n\n# Find all CSV files\nfile_paths = glob.glob('data\/*.csv')\n\n# Read and combine\ndfs = []\nfor file_path in file_paths:\n    df = pd.read_csv(file_path)\n    # Add source file as column\n    df['source_file'] = file_path.split('\/')[-1]\n    dfs.append(df)\n\n# Combine all\ndf_combined = pd.concat(dfs, ignore_index=True)\n\nprint(f\"\u2705 Processed {len(file_paths)} files, total {len(df_combined)} rows\")\n```\n\n## Best Practices\n\n1. **Check Data First**: Always use `df.head()`, `df.info()`, `df.describe()` to understand data\n2. **Copy Before Modify**: Use `df.copy()` to avoid modifying original data\n3. **Chain Operations**: Use method chaining for readability: `df.dropna().drop_duplicates().reset_index(drop=True)`\n4. **Index Management**: Reset index after filtering: `df.reset_index(drop=True)`\n5. **Memory Efficiency**: Use categorical dtype for low-cardinality string columns\n6. **Vectorization**: Avoid loops; use vectorized operations (numpy, pandas built-ins)\n7. **Documentation**: Comment complex transformations\n8. **Validation**: Check data after each major transformation\n\n## Troubleshooting\n\n### Issue: \"SettingWithCopyWarning\"\n**Solution**: Use `.copy()` to create explicit copy\n```python\ndf_subset = df[df['expression'] > 10].copy()\ndf_subset['new_col'] = values  # No warning\n```\n\n### Issue: \"Memory error with large datasets\"\n**Solution**: Process in chunks\n```python\nchunk_size = 10000\nchunks = []\nfor chunk in pd.read_csv('large_file.csv', chunksize=chunk_size):\n    # Process chunk\n    processed = chunk[chunk['expression'] > 0]\n    chunks.append(processed)\n\ndf = pd.concat(chunks, ignore_index=True)\n```\n\n### Issue: \"Key error when merging\"\n**Solution**: Check column names and presence\n```python\nprint(\"Columns in df1:\", df1.columns.tolist())\nprint(\"Columns in df2:\", df2.columns.tolist())\n\n# Use left_on\/right_on if names differ\nmerged = pd.merge(df1, df2, left_on='gene_name', right_on='gene_id')\n```\n\n### Issue: \"Data types mismatch in merge\"\n**Solution**: Ensure consistent types\n```python\ndf1['gene'] = df1['gene'].astype(str)\ndf2['gene'] = df2['gene'].astype(str)\nmerged = pd.merge(df1, df2, on='gene')\n```\n\n### Issue: \"Index alignment errors\"\n**Solution**: Reset index or specify `ignore_index=True`\n```python\ndf_combined = pd.concat([df1, df2], ignore_index=True)\n```\n\n## Critical API Reference - DataFrame vs Series Attributes\n\n### IMPORTANT: `.dtype` vs `.dtypes` - Common Pitfall!\n\n**CORRECT usage:**\n```python\n# For DataFrame - use .dtypes (PLURAL) to get all column types\ndf.dtypes  # Returns Series with column names as index, dtypes as values\n\n# For a single column (Series) - use .dtype (SINGULAR)\ndf['column_name'].dtype  # Returns single dtype object\n\n# Check specific column type\nif df['expression'].dtype == 'float64':\n    print(\"Expression is float64\")\n\n# Check all column types\nprint(df.dtypes)  # Shows dtype for each column\n```\n\n**WRONG - DO NOT USE:**\n```python\n# WRONG! DataFrame does NOT have .dtype (singular)\n# df.dtype  # AttributeError: 'DataFrame' object has no attribute 'dtype'\n\n# WRONG! This will fail\n# if df.dtype == 'float64':  # ERROR!\n```\n\n### DataFrame Type Inspection Methods\n\n```python\n# Get dtypes for all columns\ndf.dtypes\n\n# Get detailed info including dtypes\ndf.info()\n\n# Check if column is numeric\npd.api.types.is_numeric_dtype(df['column'])\n\n# Check if column is categorical\npd.api.types.is_categorical_dtype(df['column'])\n\n# Select columns by dtype\nnumeric_cols = df.select_dtypes(include=['number'])\nstring_cols = df.select_dtypes(include=['object', 'string'])\n```\n\n### Series vs DataFrame - Key Differences\n\n| Attribute\/Method | Series | DataFrame |\n|-----------------|--------|-----------|\n| `.dtype` | \u2705 Returns single dtype | \u274c AttributeError |\n| `.dtypes` | \u274c AttributeError | \u2705 Returns Series of dtypes |\n| `.shape` | `(n,)` tuple | `(n, m)` tuple |\n| `.values` | 1D array | 2D array |\n\n## Technical Notes\n\n- **Libraries**: Uses `pandas` (1.x+), `numpy`, `scikit-learn` (widely supported)\n- **Execution**: Runs locally in the agent's sandbox\n- **Compatibility**: Works with ALL LLM providers (GPT, Gemini, Claude, DeepSeek, Qwen, etc.)\n- **Performance**: Pandas is optimized with C backend; most operations are fast for <1M rows\n- **Memory**: Pandas DataFrames store data in memory; use chunking for very large files\n- **Precision**: Numeric operations use float64 by default (can use float32 to save memory)\n\n\n## Input Validation\n\nThis skill accepts requests that match the documented purpose of `data-transform` and include enough context to complete the workflow safely.\n\nDo not continue the workflow when the request is out of scope, missing a critical input, or would require unsupported assumptions. Instead respond:\n\n> `data-transform` only handles its documented workflow. Please provide the missing required inputs or switch to a more suitable skill.\n\n## References\n- pandas documentation: https:\/\/pandas.pydata.org\/docs\/\n- pandas user guide: https:\/\/pandas.pydata.org\/docs\/user_guide\/index.html\n- scikit-learn preprocessing: https:\/\/scikit-learn.org\/stable\/modules\/preprocessing.html\n- pandas cheat sheet: https:\/\/pandas.pydata.org\/Pandas_Cheat_Sheet.pdf\n","use_cases":["Clean and preprocess raw data for medical research","Normalize or scale numeric features in gene expression datasets","Reshape data between wide and long formats for analysis","Handle missing values in clinical or genomic datasets","Filter and subset datasets based on gene expression or cell type","Merge multiple datasets for comprehensive analysis"],"limitations":[],"compatibility":[],"setup_tip":null,"sample_input":null,"sample_output":null,"source_url":"https:\/\/github.com\/aipoch\/medical-research-skills\/blob\/686e09dfdb45d9fa1a08664f06bb93769b3c9d91\/scientific-skills\/Data%20Analysis\/data-transform\/SKILL.md","source_commit":"686e09dfdb45d9fa1a08664f06bb93769b3c9d91","license":"MIT","version":null,"listing_approved_at":"2026-11-24","created_at":"2026-11-23T11:21:01.000000Z","updated_at":"2026-11-24T07:14:40.000000Z","seo_title":"Data Transformation for Medical Research","seo_description":"Transform, clean, reshape, and preprocess data using pandas and numpy. Works with any LLM provider including GPT, Gemini, and Claude.","seo_keywords":["data transformation for medical research","gene expression data preprocessing","data cleaning for genomic datasets","reshape data for analysis","normalize gene expression data","filter datasets by cell type"]}}