Python Code executes arbitrary Python code and returns the result. Use this node when you need custom logic, calculations, or data processing that isn’t available in existing nodes. Supports all standard libraries plus popular data analysis tools like pandas, numpy, and more.

When to Use It

⚠️ Advanced Node: Use this only when existing nodes cannot accomplish your task. Always check if a specialized node exists first.
  • Perform complex calculations not available in existing math/utility nodes
  • Transform data in highly specific ways not supported by existing data nodes
  • Apply advanced statistical analysis, machine learning, or scientific computing
  • Parse or manipulate complex data structures requiring custom logic
  • Create sophisticated business logic that combines multiple operations
  • Process data with specialized libraries (computer vision, audio analysis, NLP)
Before using this node: Review available nodes in AI, Utilities, and other categories to ensure no existing solution meets your needs.

Inputs

FieldTypeRequiredDescription
VariablesVariablesNoDynamic data from other nodes injected into your code context
CodeCodeYesThe Python code to execute (result must be on the last line)

Outputs

OutputDescription
DataThe results value returned by your code execution

Credit Cost

2 credits per execution.

How It Works

Python Code executes your custom Python script in a Jupyter notebook-like environment with access to extensive data science libraries. Like in Jupyter notebooks, only the result of the last line is returned as output. Variables from other nodes are automatically injected into the execution context, so you can reference them directly in your code. Key Features:
  • Jupyter notebook-style execution (last line becomes the output)
  • Access to 30+ pre-installed data science libraries
  • Automatic variable injection from workflow data
  • JSON-safe output formatting
  • Secure execution environment

Available Libraries

The Python Code node includes 30+ pre-installed libraries for data science, web scraping, visualization, and more:
LibraryVersionUse Case
aiohttpv3.9.3Asynchronous HTTP client/server
beautifulsoup4v4.12.3Web scraping and HTML/XML parsing
bokehv3.3.4Interactive visualization
gensimv4.3.2Topic modeling and document analysis
imageiov2.34.0Image I/O operations
joblibv1.3.2Parallel computing and model persistence
librosav0.10.1Audio analysis and music information retrieval
matplotlibv3.8.3Data visualization and plotting
nltkv3.8.1Natural language processing
numpyv1.26.4Numerical computing and arrays
opencv-pythonv4.9.0.80Computer vision and image processing
openpyxlv3.1.2Excel file reading and writing
pandasv1.5.3Data manipulation and analysis
plotlyv5.19.0Interactive web-based visualizations
pytestv8.1.0Testing framework
python-docxv1.1.0Microsoft Word document manipulation
pytzv2024.1Timezone handling
requestsv2.26.0HTTP requests and API calls
scikit-imagev0.22.0Image processing algorithms
scikit-learnv1.4.1.post1Machine learning library
scipyv1.12.0Scientific computing
seabornv0.13.2Statistical data visualization
soundfilev0.12.1Audio file I/O
spacyv3.7.4Advanced natural language processing
sympyv1.12Symbolic mathematics
textblobv0.18.0Simple text processing
tornadov6.4Web framework and networking
urllib3v1.26.7HTTP client library
xarrayv2024.2.0Multi-dimensional arrays and datasets
xlrdv2.0.1Excel file reading
Plus all standard Python libraries (json, datetime, math, statistics, etc.)

Code Requirements

Jupyter-Style Execution:
  • Works like a Jupyter notebook - only the last line’s result is returned
  • No need for explicit return statements
  • The final expression becomes the output automatically
Return Value:
  • Place your result as the final line of code
  • Must be JSON-safe types: dict, list, str, int, float, bool, or None
  • No print() statements for output - use the last line instead
Valid Examples:
# Simple calculation (last line is the result)
total_sales = sum(row['amount'] for row in sales_data)
average_sales = total_sales / len(sales_data)
average_sales  # This becomes the output

# Multiple values as dict
data_summary = {
    "total": sum(amounts), 
    "count": len(amounts),
    "average": sum(amounts) / len(amounts)
}
data_summary  # This becomes the output

# Processed data list
processed = [{"name": item["name"].upper(), "score": item["score"] * 1.1} for item in raw_data]
processed  # This becomes the output
Invalid Returns:
  • pandas DataFrames (convert to dict/list first: df.to_dict('records'))
  • numpy arrays (use .tolist())
  • Custom objects or functions
  • Complex nested objects

Variables Usage

Variables from other nodes are automatically available in your code context: Setup Variables:
{
  "sales_data": "{{sheetsNode.data}}",
  "target_amount": "{{inputNode.data}}",
  "account_ids": "{{adsNode.data}}"
}
Use in Code:
# Variables are already available - no need to define them
total_sales = sum(row['amount'] for row in sales_data)
performance = total_sales / target_amount

{"total": total_sales, "performance_ratio": performance}

Examples

Example 1: Calculate Campaign Performance

Variables:
{
  "campaigns": "{{adsNode.data}}",
  "target_roas": "{{inputNode.data}}"
}
Code:
results = []
for campaign in campaigns:
    roas = campaign['revenue'] / campaign['cost'] if campaign['cost'] > 0 else 0
    performance = "Above Target" if roas >= target_roas else "Below Target"
    
    results.append({
        "campaign_name": campaign['name'],
        "roas": round(roas, 2),
        "status": performance
    })

results

Example 2: Data Cleaning and Transformation

Variables:
{
  "raw_data": "{{dataNode.data}}"
}
Code:
import pandas as pd

# Convert to DataFrame for easier processing
df = pd.DataFrame(raw_data)

# Clean and transform
df['email'] = df['email'].str.lower().str.strip()
df['phone'] = df['phone'].str.replace(r'[^\d]', '', regex=True)
df = df.dropna(subset=['email'])

# Convert back to list of dicts
df.to_dict('records')

FAQ