add_column
Add a new column to your CSV data by specifying a name, optional value, or formula. Simplify data manipulation and enhance your dataset structure for better analysis.
Instructions
Add a new column to the dataframe.
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| formula | No | ||
| name | Yes | ||
| session_id | Yes | ||
| value | No |
Implementation Reference
- The core handler function that executes the add_column tool logic: validates session, checks if column exists, adds column using constant value, list, or formula via df.eval(), records the operation in history, and returns success status with updated columns.async def add_column( session_id: str, name: str, value: Any = None, formula: Optional[str] = None, ctx: Context = None ) -> Dict[str, Any]: """ Add a new column to the dataframe. Args: session_id: Session identifier name: Name for the new column value: Default value for all rows (scalar or list) formula: Python expression to calculate values (e.g., "col1 + col2") ctx: FastMCP context Returns: Dict with success status """ try: manager = get_session_manager() session = manager.get_session(session_id) if not session or session.df is None: return {"success": False, "error": "Invalid session or no data loaded"} df = session.df if name in df.columns: return {"success": False, "error": f"Column '{name}' already exists"} if formula: # Evaluate formula in the context of the dataframe try: session.df[name] = df.eval(formula) except Exception as e: return {"success": False, "error": f"Formula evaluation failed: {str(e)}"} elif isinstance(value, list): if len(value) != len(df): return {"success": False, "error": f"Value list length ({len(value)}) doesn't match row count ({len(df)})"} session.df[name] = value else: # Scalar value or None session.df[name] = value session.record_operation(OperationType.ADD_COLUMN, { "name": name, "value": str(value) if value is not None else None, "formula": formula }) return { "success": True, "column_added": name, "columns": session.df.columns.tolist() } except Exception as e: logger.error(f"Error adding column: {str(e)}") return {"success": False, "error": str(e)}
- src/csv_editor/server.py:239-247 (registration)Registers the 'add_column' tool with FastMCP using the @mcp.tool decorator. This wrapper function delegates to the actual implementation imported as _add_column from transformations.py.async def add_column( session_id: str, name: str, value: Any = None, formula: Optional[str] = None, ctx: Context = None ) -> Dict[str, Any]: """Add a new column to the dataframe.""" return await _add_column(session_id, name, value, formula, ctx)
- Defines OperationType enum including ADD_COLUMN, used for recording operations in session history and potentially for schema/validation of tool usage.class OperationType(str, Enum): """Types of operations that can be performed.""" LOAD = "load" FILTER = "filter" SORT = "sort" TRANSFORM = "transform" AGGREGATE = "aggregate" EXPORT = "export" ANALYZE = "analyze" UPDATE_COLUMN = "update_column" ADD_COLUMN = "add_column" REMOVE_COLUMN = "remove_column" RENAME = "rename" SELECT = "select" CHANGE_TYPE = "change_type" FILL_MISSING = "fill_missing" REMOVE_DUPLICATES = "remove_duplicates" GROUP_BY = "group_by" VALIDATE = "validate" PROFILE = "profile" QUALITY_CHECK = "quality_check" ANOMALY_DETECTION = "anomaly_detection"