Skip to content
The Chat Archive
gemini-2.5-pro· Google LMArena Human Preference 140K

i'm writing a prompt to translate code from sas to python, write for me a prompt that…

  1. User

    i'm writing a prompt to translate code from sas to python, write for me a prompt that takes in consideration all diferences between sas and python and clear prompt to handle all instructions in sas

  2. Assistant

    Of course. Here is a comprehensive and well-structured prompt designed to guide an AI in translating SAS code to Python. It covers the core differences, specifies the desired output format, and provides clear instructions for handling various SAS constructs.

    This prompt is designed to be a "master prompt" that you can save and reuse. You just need to paste your SAS code at the end.


    The Master Prompt for SAS to Python Translation

    You are an expert programmer with deep knowledge of both SAS and Python data science ecosystems. Your task is to act as a code translator, migrating legacy SAS code to modern, efficient, and idiomatic Python.

    When I provide you with a SAS script, you will translate it into a Python script that achieves the exact same outcome. Your translation must adhere to the following principles and mappings:

    1. Core Translation Philosophy:

    • Idiomatic Python: The output should not be a line-for-line, literal translation. Instead, it must be "Pythonic," leveraging the strengths of Python and its libraries. For instance, prefer vectorized operations with Pandas over explicit for loops that mimic the SAS DATA step's implicit loop.
    • Readability and Maintainability: The Python code should be clean, well-structured, and include comments to explain complex logic or choices, especially where the Python approach differs significantly from SAS.
    • Efficiency: Use efficient methods. For example, use pd.merge() instead of a slow, looping equivalent.

    2. Specific SAS to Python Mappings:

    • SAS Datasets -> Pandas DataFrames:

      • All SAS datasets (WORK.mydataset, libname.dataset) should be handled as Pandas DataFrames. Assume input datasets are either pre-loaded into a DataFrame with a similar name (e.g., mydataset) or read from a file.
    • The DATA Step:

      • SET: Reading a single dataset translates to creating a copy of a DataFrame (e.g., new_df = old_df.copy()).
      • MERGE & BY: Translate to pandas.merge(). Correctly identify the merge keys from the BY statement and the type of join (e.g., inner, left, right).
      • Variable Creation/Modification: A simple new_var = old_var * 2; becomes df['new_var'] = df['old_var'] * 2.
      • IF/THEN/ELSE Logic:
        • For conditional variable assignment, use numpy.where() or df.loc[] with boolean masking. Example: IF condition THEN x=1; ELSE x=0; becomes df['x'] = np.where(condition, 1, 0).
      • Subsetting Data (IF condition; or WHERE statement): Translate this to Pandas filtering. Example: IF age > 30; becomes df = df[df['age'] > 30].
      • RETAIN Statement: This is a critical concept. RETAIN carries a value from one row to the next. The most common Python equivalent is pandas.DataFrame.ffill() (forward fill). Clearly state when you are using .ffill() to replicate a RETAIN.
      • LAG Function: Translate LAG(variable) to df['variable'].shift().
      • FIRST. and LAST. Processing: Translate logic using df.groupby('by_variable').cumcount() or by identifying the first/last occurrences within groups using methods like df.duplicated(subset=['by_variable'], keep='first').
      • DO Loops: A DO loop inside a DATA step often creates new rows. This can be complex. Translate this using methods like pd.concat after generating new rows in a loop or using DataFrame expansion techniques.
    • PROC (Procedures):

      • PROC SORT: Translate to df.sort_values(by=['vars'], ascending=[True/False]).
      • PROC PRINT: Translate to print(df.head()) or simply display(df) in a notebook context.
      • PROC MEANS/PROC SUMMARY: Translate to df.describe() for basic stats or df.groupby('class_vars').agg({...}) for grouped summaries.
      • PROC FREQ:
        • For one-way frequencies, use df['variable'].value_counts().
        • For two-way frequencies (cross-tabulation), use pd.crosstab(df['var1'], df['var2']).
      • PROC SQL: Either translate the SQL logic directly into equivalent Pandas operations (preferred) or use the pandasql library if the logic is very complex. Pandas operations are generally more idiomatic.
      • PROC IMPORT/INFILE: Translate to pandas.read_csv(), pandas.read_excel(), pandas.read_fwf(), etc.
      • PROC EXPORT: Translate to df.to_csv(), df.to_excel(), etc.
      • PROC TRANSPOSE: Translate to df.pivot() or df.melt(), depending on the specific transposition logic. df.T can be used for simple matrix transposition.
      • Statistical PROCs (PROC REG, PROC LOGISTIC, PROC GLM): Translate using the statsmodels or scikit-learn libraries.
        • PROC REG -> statsmodels.api.OLS()
        • PROC LOGISTIC -> statsmodels.api.Logit() or sklearn.linear_model.LogisticRegression()
    • SAS Macros (%MACRO):

      • Translate SAS macros into Python functions. Macro variables (&myvar) should become function parameters. This promotes code reuse and modularity in Python.

    3. Required Output Format:

    Your response must be structured in three parts:

    Part 1: Required Python Libraries List all the necessary Python libraries with their common import aliases (e.g., import pandas as pd, import numpy as np).

    Part 2: Translated Python Code Provide the complete, runnable Python script. The code should be enclosed in a single markdown code block.

    Part 3: Explanation Provide a step-by-step explanation of the translation.

    • Detail how each SAS DATA step or PROC was converted.
    • Explain the choices made (e.g., "I used pd.merge for the MERGE statement with a 'left' join because...").
    • Explicitly call out any tricky translations like RETAIN or FIRST./LAST. processing and justify the Python equivalent you chose.
    • If the SAS code's intent is ambiguous, state your assumptions.

    Translate the following SAS code:

    [YOUR SAS CODE HERE]
    

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.