python reference guide for ibm spss statistics

304
Python Reference Guide for IBM SPSS Statistics

Upload: gino-vape

Post on 18-Aug-2015

346 views

Category:

Documents


14 download

DESCRIPTION

This book is about the implementation of python scripts in Spss. Really easy and clear to apply. Higly reccomended.

TRANSCRIPT

Python Reference Guide for IBM SPSSStatistics

NoteBefore using this information and the product it supports, read the information in Notices on page 275.Product InformationThis edition applies to version 22, release 0, modification 0 of IBM SPSS Statistics and to all subsequent releases andmodifications until otherwise indicated in new editions.ContentsOverview. . . . . . . . . . . . . . xiPart 1. Python Integration Packagefor IBM SPSS Statistics . . . . . . . 1Introduction to Python Programs . . . . 3Working with Python Program Blocks . . . . . . 4Basic Specification for a Python Program Block . . 4Nested Program Blocks . . . . . . . . . . 5Unicode Mode. . . . . . . . . . . . . 7Python Syntax Rules. . . . . . . . . . . . 7Working with Multiple Versions of IBM SPSSStatistics . . . . . . . . . . . . . . . . 8Python and IBM SPSS Statistics Working Directories 9Running IBM SPSS Statistics from an External PythonProcess . . . . . . . . . . . . . . . . 9Localizing Output from Python Programs . . . . 11Modifying the Python code . . . . . . . . 12Extracting translatable text . . . . . . . . 12Translating the pot file. . . . . . . . . . 13Installing the mo files. . . . . . . . . . 13Python Functions and Classes . . . . 15spss.ActiveDataset Function . . . . . . . . . 16spss.AddProcedureFootnotes Function . . . . . 16spss.BasePivotTable Class. . . . . . . . . . 16Creating Pivot Tables with the SimplePivotTableMethod. . . . . . . . . . . . . . . 18General Approach to Creating Pivot Tables . . . 19spss.BasePivotTable Methods . . . . . . . 23spss.CellText Class . . . . . . . . . . . 33Creating a Warnings Table . . . . . . . . 36spss.BaseProcedure Class . . . . . . . . . . 37spss.CreateXPathDictionary Function . . . . . . 39spss.Cursor Class . . . . . . . . . . . . 40Read Mode . . . . . . . . . . . . . 40Write Mode . . . . . . . . . . . . . 41Append Mode . . . . . . . . . . . . 43spss.Cursor Methods . . . . . . . . . . 44spss.Dataset Class . . . . . . . . . . . . 56cases Property . . . . . . . . . . . . 59name Property . . . . . . . . . . . . 59varlist Property . . . . . . . . . . . . 59dataFileAttributes Property . . . . . . . . 59multiResponseSet Property . . . . . . . . 60optimized Property . . . . . . . . . . . 61close Method . . . . . . . . . . . . . 62deepCopy Method. . . . . . . . . . . 62CaseList Class . . . . . . . . . . . . 62VariableList Class . . . . . . . . . . . 65Variable Class . . . . . . . . . . . . 67spss.DataStep Class. . . . . . . . . . . . 71spss.DeleteXPathHandle Function. . . . . . . 72spss.EndDataStep Function . . . . . . . . . 72spss.EndProcedure Function . . . . . . . . . 72spss.EvaluateXPath Function . . . . . . . . 72spss.GetCaseCount Function. . . . . . . . . 73spss.GetDataFileAttributeNames Function . . . . 73spss.GetDataFileAttributes Function . . . . . . 73spss.GetDatasets Function . . . . . . . . . 73spss.GetDefaultPlugInVersion Function . . . . . 74spss.GetFileHandles Function . . . . . . . . 74spss.GetHandleList Function. . . . . . . . . 74spss.GetImage Function . . . . . . . . . . 74spss.GetLastErrorLevel andspss.GetLastErrorMessage Functions . . . . . . 75spss.GetMultiResponseSetNames Function. . . . 76spss.GetMultiResponseSet Function . . . . . . 76spss.GetOMSTagList Function . . . . . . . . 76spss.GetSetting Function. . . . . . . . . . 76spss.GetSplitVariableNames Function . . . . . . 77spss.GetSPSSLocale Function . . . . . . . . 77spss.GetSPSSLowHigh Function . . . . . . . 77spss.GetVarAttributeNames Function . . . . . . 77spss.GetVarAttributes Function . . . . . . . . 77spss.GetVariableCount Function . . . . . . . 78spss.GetVariableFormat Function . . . . . . . 78spss.GetVariableLabel Function . . . . . . . . 79spss.GetVariableMeasurementLevel Function . . . 79spss.GetVariableName Function . . . . . . . 79spss.GetVariableRole Function . . . . . . . . 79spss.GetVariableType Function. . . . . . . . 80spss.GetVarMissingValues Function . . . . . . 80spss.GetWeightVar Function . . . . . . . . . 81spss.GetXmlUtf16 Function . . . . . . . . . 81spss.HasCursor Function . . . . . . . . . . 81spss.IsActive Function . . . . . . . . . . . 81spss.IsOutputOn Function . . . . . . . . . 81spss.Procedure Class . . . . . . . . . . . 82spss.PyInvokeSpss.IsUTF8mode Function . . . . 82spss.PyInvokeSpss.IsXDriven Function . . . . . 82spss.SetActive Function . . . . . . . . . . 83spss.SetDefaultPlugInVersion Function . . . . . 83spss.SetMacroValue Function . . . . . . . . 83spss.SetOutput Function . . . . . . . . . . 84spss.SetOutputLanguage Function . . . . . . . 84spss.ShowInstalledPlugInVersions Function. . . . 84spss.SplitChange Function . . . . . . . . . 85spss.StartDataStep Function. . . . . . . . . 86spss.StartProcedure Function . . . . . . . . 86spss.StartSPSS Function . . . . . . . . . . 88spss.StopSPSS Function . . . . . . . . . . 89spss.Submit Function . . . . . . . . . . . 89spss.TextBlock Class . . . . . . . . . . . 90append Method. . . . . . . . . . . . 91Part 2. Python Scripting Guide forIBM SPSS Statistics. . . . . . . . 93iiiIntroduction to Python Scripts . . . . 95Working with Multiple Versions of IBM SPSSStatistics . . . . . . . . . . . . . . . 96Class Hierarchy for Scripting Facility . . . . . . 96Getting Started with Python Scripts . . . . . . 97Getting Started with Autoscripts in Python . . . 98Running Python Scripts from Python Programs 99SpssClient Class . . . . . . . . . . 101CreateNewServer Method . . . . . . . . . 101Exit Method . . . . . . . . . . . . . . 101GetActiveDataDoc Method . . . . . . . . . 102GetConfiguredServers Method. . . . . . . . 102GetCurrentDirectory Method . . . . . . . . 102GetCurrentServer Method . . . . . . . . . 102GetDataDocuments Method . . . . . . . . 102GetDefaultJCVersion Method . . . . . . . . 102GetDefaultServer Method . . . . . . . . . 103GetDesignatedOutputDoc Method . . . . . . 103GetDesignatedSyntaxDoc Method . . . . . . 103GetExportOption Method . . . . . . . . . 103GetLocale Method. . . . . . . . . . . . 103GetLocalServer Method. . . . . . . . . . 104GetOutputDocuments Method. . . . . . . . 104GetPreference Method . . . . . . . . . . 104GetScriptContext Method . . . . . . . . . 104GetSPSSOptions Method . . . . . . . . . 104GetSPSSPath Method. . . . . . . . . . . 105GetSPSSVersion Method . . . . . . . . . . 105GetSyntaxDocuments Method . . . . . . . . 105GetUIAlerts Method. . . . . . . . . . . 106IsDataDocInUse Method. . . . . . . . . . 106IsDistributedMode. . . . . . . . . . . . 106IsOptionAvailable Method. . . . . . . . . 106LogToViewer Method. . . . . . . . . . . 107NewDataDoc Method . . . . . . . . . . 107NewOutputDoc Method. . . . . . . . . . 108NewSyntaxDoc Method . . . . . . . . . . 108OpenDataDoc Method . . . . . . . . . . 108OpenOutputDoc Method . . . . . . . . . 108OpenSyntaxDoc Method. . . . . . . . . . 109RunSyntax Method . . . . . . . . . . . 109SaveServers Method . . . . . . . . . . . 110ScriptParameter Method. . . . . . . . . . 110SetCurrentDirectory Method . . . . . . . . 110SetDefaultJCVersion Method . . . . . . . . 111SetExportOption Method . . . . . . . . . 111SetPreference Method. . . . . . . . . . . 111SetUIAlerts Method . . . . . . . . . . . 112StartClient Method . . . . . . . . . . . 112StopClient Method . . . . . . . . . . . 112_heartBeat Method . . . . . . . . . . . 112Datasets and Data Editor Windows 115SpssDataDoc Class . . . . . . . . . . . 115CloseDocument Method . . . . . . . . . 115GetCaseCount Method . . . . . . . . . 115GetDatasetName Method . . . . . . . . 115GetDataUI Method . . . . . . . . . . 115GetDocumentPath Method. . . . . . . . 116GetMenuTable Method . . . . . . . . . 116GetVariableCount Method . . . . . . . . 116IsActiveDataDoc Method . . . . . . . . 116IsEqualTo Method . . . . . . . . . . . 116IsModified Method . . . . . . . . . . 116IsPromptToSave Method. . . . . . . . . 117SaveAs Method. . . . . . . . . . . . 117SetAsActiveDataDoc Method . . . . . . . 117SetDatasetName Method . . . . . . . . 117SetModified Method. . . . . . . . . . 118SetPromptToSave Method . . . . . . . . 118DataDocsList Class . . . . . . . . . . . 118GetItemAt Method . . . . . . . . . . 118Size Method . . . . . . . . . . . . . 118SpssDataUI Class . . . . . . . . . . . . 119GetHeight Method. . . . . . . . . . . 119GetLeft Method. . . . . . . . . . . . 119GetShowGridLines Method. . . . . . . . 119GetShowValueLabels Method. . . . . . . 119GetTitleText Method . . . . . . . . . . 119GetTop Method. . . . . . . . . . . . 119GetVisible Method. . . . . . . . . . . 120GetWidth Method . . . . . . . . . . . 120GetWindowState Method . . . . . . . . 120InvokeDialog Method . . . . . . . . . 120PrintDataDoc Method . . . . . . . . . 121SetHeight Method . . . . . . . . . . . 121SetLeft Method . . . . . . . . . . . . 121SetShowGridLines Method . . . . . . . . 121SetShowValueLabels Method . . . . . . . 121SetTop Method . . . . . . . . . . . . 122SetVisible Method . . . . . . . . . . . 122SetWidth Method. . . . . . . . . . . 122SetWindowState Method . . . . . . . . 122Output Documents and ViewerWindows . . . . . . . . . . . . . 123SpssOutputDoc Class. . . . . . . . . . . 123ClearSelection Method . . . . . . . . . 123CloseDocument Method. . . . . . . . . 123Copy Method . . . . . . . . . . . . 124CopySpecial Method. . . . . . . . . . 124CreateHeaderItem Method. . . . . . . . 125CreateImageChartItem Method . . . . . . 125CreateTextItem Method. . . . . . . . . 125CreateTitleItem Method. . . . . . . . . 126Cut Method . . . . . . . . . . . . . 126Delete Method. . . . . . . . . . . . 126Demote Method . . . . . . . . . . . 126ExportCharts Method . . . . . . . . . 127ExportDocument Method . . . . . . . . 127GetCurrentItem Method . . . . . . . . . 128GetDocumentPath Method. . . . . . . . 128GetFooterText Method . . . . . . . . . 128GetHeaderText Method. . . . . . . . . 129GetMenuTable Method . . . . . . . . . 129GetOutputItems Method. . . . . . . . . 129GetOutputOptions Method . . . . . . . . 129GetOutputUI Method. . . . . . . . . . 130GetPrintOptions Method . . . . . . . . 131InsertTable Method . . . . . . . . . . 131iv Python Reference Guide for IBM SPSS StatisticsIsDesignatedOutputDoc Method. . . . . . 132IsEqualTo Method . . . . . . . . . . . 132IsModified Method . . . . . . . . . . 132IsPromptToSave Method. . . . . . . . . 132Paste Method . . . . . . . . . . . . 132PasteBefore Method . . . . . . . . . . 133PrintRange Method . . . . . . . . . . 133Promote Method . . . . . . . . . . . 133SaveAs Method . . . . . . . . . . . 133SelectAll Method . . . . . . . . . . . 134SelectAllCharts Method. . . . . . . . . 134SelectAllLogs Method . . . . . . . . . 134SelectAllModels Method. . . . . . . . . 134SelectAllNotes Method . . . . . . . . . 134SelectAllNotesEx Method . . . . . . . . 134SelectAllOther Method . . . . . . . . . 135SelectAllTables Method. . . . . . . . . 135SelectAllTablesEx Method . . . . . . . . 135SelectAllText Method . . . . . . . . . . 135SelectAllTitles Method . . . . . . . . . 135SelectAllWarnings Method. . . . . . . . 135SelectAllWarningsEx Method . . . . . . . 135SelectLastOutput Method . . . . . . . . 136SetAsDesignatedOutputDoc Method. . . . . 136SetFooterText Method . . . . . . . . . 136SetHeaderText Method . . . . . . . . . 136SetModified Method. . . . . . . . . . 136SetOutputOptions Method. . . . . . . . 136SetPrintOptions Method. . . . . . . . . 138SetPromptToSave Method . . . . . . . . 139OutputDocsList Class . . . . . . . . . . 139GetItemAt Method . . . . . . . . . . 139Size Method. . . . . . . . . . . . . 140OutputItemList Class . . . . . . . . . . . 140GetItemAt Method . . . . . . . . . . 140Size Method. . . . . . . . . . . . . 140SpssOutputUI Class . . . . . . . . . . . 140GetHeight Method . . . . . . . . . . 140GetLeft Method . . . . . . . . . . . 141GetSplitterPosition Method . . . . . . . . 141GetTitleText Method. . . . . . . . . . 141GetTop Method. . . . . . . . . . . . 141GetVisible Method. . . . . . . . . . . 141GetWidth Method . . . . . . . . . . . 141GetWindowState Method . . . . . . . . 141InvokeDialog Method . . . . . . . . . 142PrintOutputDoc Method. . . . . . . . . 142SetHeight Method . . . . . . . . . . . 142SetLeft Method . . . . . . . . . . . . 143SetSplitterPosition Method. . . . . . . . 143SetTop Method . . . . . . . . . . . . 143SetVisible Method . . . . . . . . . . . 143SetWidth Method. . . . . . . . . . . 143SetWindowState Method . . . . . . . . 144Syntax Documents and Syntax EditorWindows . . . . . . . . . . . . . 145SpssSyntaxDoc Class . . . . . . . . . . . 145CloseDocument Method. . . . . . . . . 145GetDocumentPath Method. . . . . . . . 145GetMenuTable Method . . . . . . . . . 145GetSyntax Method. . . . . . . . . . . 146GetSyntaxUI Method . . . . . . . . . . 146IsDesignatedSyntaxDoc Method . . . . . . 146IsEqualTo Method . . . . . . . . . . . 146IsModified Method . . . . . . . . . . 146IsPromptToSave Method. . . . . . . . . 146RunSyntax Method . . . . . . . . . . 147SaveAs Method . . . . . . . . . . . 147SetAsDesignatedSyntaxDoc Method . . . . . 147SetModified Method. . . . . . . . . . 147SetPromptToSave Method . . . . . . . . 148SetSyntax Method . . . . . . . . . . . 148SyntaxDocsList Class . . . . . . . . . . . 148GetItemAt Method . . . . . . . . . . 149Size Method. . . . . . . . . . . . . 149SpssSyntaxUI Class . . . . . . . . . . . 149GetHeight Method . . . . . . . . . . 149GetLeft Method . . . . . . . . . . . 149GetTitleText Method. . . . . . . . . . 149GetTop Method. . . . . . . . . . . . 149GetVisible Method. . . . . . . . . . . 150GetWidth Method . . . . . . . . . . . 150GetWindowState Method . . . . . . . . 150InvokeDialog Method . . . . . . . . . 150PrintSyntaxDoc Method . . . . . . . . . 151SetHeight Method . . . . . . . . . . . 151SetLeft Method . . . . . . . . . . . . 151SetTop Method . . . . . . . . . . . . 151SetVisible Method . . . . . . . . . . . 151SetWidth Method. . . . . . . . . . . 152SetWindowState Method . . . . . . . . 152Output Items. . . . . . . . . . . . 153SpssOutputItem Class . . . . . . . . . . 153ConvertToStdTable Method. . . . . . . . 153ExportToDocument Method . . . . . . . 153ExportToImage Method. . . . . . . . . 154GetAlignment Method . . . . . . . . . 154GetDescription Method. . . . . . . . . 155GetHeight Method . . . . . . . . . . 155GetPageBreak Method . . . . . . . . . 155GetParentItem Method . . . . . . . . . 155GetProcedureName Method . . . . . . . 155GetSpecificType Method. . . . . . . . . 155GetSubType Method. . . . . . . . . . 156GetTreeLevel Method. . . . . . . . . . 156GetType Method . . . . . . . . . . . 156GetTypeString Method . . . . . . . . . 157GetWidth Method . . . . . . . . . . . 157GetXML Method . . . . . . . . . . . 157IsCurrentItem Method . . . . . . . . . 157IsEditable Method. . . . . . . . . . . 158IsEqualTo Method . . . . . . . . . . . 158IsSelected Method . . . . . . . . . . . 158IsVisible Method . . . . . . . . . . . 158SetAlignment Method . . . . . . . . . 158SetCurrentItem Method. . . . . . . . . 159SetDescription Method . . . . . . . . . 159SetHeight Method . . . . . . . . . . . 159SetPageBreak Method . . . . . . . . . 159SetProcedureName Method. . . . . . . . 159Contents vSetSelected Method . . . . . . . . . . 159SetSubType Method . . . . . . . . . . 160SetTreeLevel Method . . . . . . . . . . 160SetVisible Method . . . . . . . . . . . 160SetWidth Method. . . . . . . . . . . 160SpssChartItem Class . . . . . . . . . . . 160SetXML Method . . . . . . . . . . . 161SPSSSubtype Method. . . . . . . . . . 161SpssModelItem Class . . . . . . . . . . . 161ExportAllViews Method . . . . . . . . . 162SetXML Method . . . . . . . . . . . 162SpssHeaderItem Class . . . . . . . . . . 162GetChildCount Method. . . . . . . . . 163GetChildItem Method . . . . . . . . . 163InsertChildItem Method . . . . . . . . . 163IsExpanded Method . . . . . . . . . . 164RemoveChildItem Method. . . . . . . . 164SetExpanded Method. . . . . . . . . . 164SpssLogItem Class. . . . . . . . . . . . 164Append Method . . . . . . . . . . . 165GetTextContents Method . . . . . . . . 165SetTextContents Method. . . . . . . . . 165SpssTextItem Class . . . . . . . . . . . 165GetTextContents Method . . . . . . . . 165SetTextContents Method. . . . . . . . . 166SpssTitleItem Class . . . . . . . . . . . 166GetTextContents Method . . . . . . . . 166SetTextContents Method. . . . . . . . . 166Menus . . . . . . . . . . . . . . 167MenuTableList Class. . . . . . . . . . . 167GetItemAt Method . . . . . . . . . . 167Size Method. . . . . . . . . . . . . 167SpssMenuItem Class. . . . . . . . . . . 167GetTextContents Method . . . . . . . . 167Pivot Tables . . . . . . . . . . . . 169Pivot Tables . . . . . . . . . . . . . . 169Compatibility with previous releases . . . . 170SpssPivotTable Class. . . . . . . . . . . 170Autofit Method. . . . . . . . . . . . 171ClearSelection Method . . . . . . . . . 171ColumnLabelArray Method . . . . . . . 171DataCellArray Method . . . . . . . . . 171DisplayTableByRows Method. . . . . . . 171FootnotesArray Method . . . . . . . . . 171GetCaptionText Method . . . . . . . . . 172GetFootnoteMarkersPosition Method . . . . 172GetFootnoteMarkersStyle Method . . . . . 172GetHeight Method . . . . . . . . . . 172GetRotateColumnLabels Method. . . . . . 172GetRotateRowLabels Method . . . . . . . 173GetTitleText Method. . . . . . . . . . 173GetUpdateScreen Method . . . . . . . . 173GetVarNamesDisplay Method . . . . . . . 173GetVarValuesDisplay Method. . . . . . . 173GetWidowOrphanLines Method . . . . . . 174GetWidth Method . . . . . . . . . . . 174Group Method . . . . . . . . . . . . 174HideCaption Method. . . . . . . . . . 175HideFootnote Method . . . . . . . . . 175HideTitle Method. . . . . . . . . . . 175InsertFootnote Method . . . . . . . . . 175IsDisplayTableByRows Method . . . . . . 175LayerLabelArray Method . . . . . . . . 175NavigateToFirstRow Method . . . . . . . 176NavigateToLastRow Method . . . . . . . 176NavigateToNextRows Method . . . . . . . 176NavigateToPreviousRows Method . . . . . 176NumericFormat Method. . . . . . . . . 176PivotManager Method . . . . . . . . . 177RowLabelArray Method. . . . . . . . . 177SelectAllFootnotes Method . . . . . . . . 177SelectCaption Method . . . . . . . . . 177SelectCorner Method . . . . . . . . . . 177SelectTable Method . . . . . . . . . . 177SelectTableBody Method. . . . . . . . . 177SelectTitle Method. . . . . . . . . . . 178SetBackgroundColor Method . . . . . . . 178SetBottomMargin Method . . . . . . . . 178SetCaptionText Method. . . . . . . . . 178SetCornerText Method . . . . . . . . . 178SetDataCellWidths Method . . . . . . . . 179SetFootnoteMarkers Method . . . . . . . 179SetForegroundColor Method . . . . . . . 179SetHAlign Method . . . . . . . . . . 179SetHDecDigits Method . . . . . . . . . 179SetLeftMargin Method . . . . . . . . . 180SetRightMargin Method . . . . . . . . . 180SetRotateColumnLabels Method . . . . . . 180SetRotateRowLabels Method . . . . . . . 180SetRowsToDisplayRowCount Method . . . . 181SetRowsToDisplayTolerance Method. . . . . 181SetTableLook Method . . . . . . . . . 181SetTextColor Method . . . . . . . . . . 182SetTextFont Method . . . . . . . . . . 182SetTextHidden Method . . . . . . . . . 182SetTextSize Method . . . . . . . . . . 182SetTextStyle Method. . . . . . . . . . 182SetTextUnderlined Method . . . . . . . . 183SetTitleText Method . . . . . . . . . . 183SetTopMargin Method . . . . . . . . . 183SetUpdateScreen Method . . . . . . . . 183SetVAlign Method. . . . . . . . . . . 184SetVarNamesDisplay Method. . . . . . . 184SetVarValuesDisplay Method . . . . . . . 184SetWidowOrphanLines Method . . . . . . 185ShowAll Method . . . . . . . . . . . 185ShowAllFootnotes Method. . . . . . . . 185ShowCaption Method . . . . . . . . . 185ShowFootnote Method . . . . . . . . . 185ShowTitle Method. . . . . . . . . . . 186Ungroup Method. . . . . . . . . . . 186SpssDataCells Class . . . . . . . . . . . 186GetBackgroundColorAt Method . . . . . . 187GetBottomMarginAt Method . . . . . . . 187GetForegroundColorAt Method . . . . . . 187GetHAlignAt Method . . . . . . . . . 187GetHDecDigitsAt Method . . . . . . . . 188GetLeftMarginAt Method . . . . . . . . 188GetNumColumns Method . . . . . . . . 188vi Python Reference Guide for IBM SPSS StatisticsGetNumericFormatAt method . . . . . . . 188GetNumericFormatAtEx method. . . . . . 189GetNumRows Method . . . . . . . . . 189GetReferredFootnotesAt Method. . . . . . 189GetRightMarginAt Method . . . . . . . . 190GetTextColorAt Method . . . . . . . . . 190GetTextFontAt Method . . . . . . . . . 190GetTextHiddenAt Method . . . . . . . . 191GetTextSizeAt Method . . . . . . . . . 191GetTextStyleAt Method. . . . . . . . . 191GetTextUnderlinedAt Method . . . . . . . 192GetTopMarginAt Method . . . . . . . . 192GetVAlignAt Method. . . . . . . . . . 192GetUnformattedValueAt Method . . . . . . 193GetValueAt Method . . . . . . . . . . 193HideFootnotesAt Method . . . . . . . . 193InsertNewFootnoteAt Method . . . . . . . 194InsertSharedFootnoteAt Method . . . . . . 194ReSizeColumn Method . . . . . . . . . 194SelectCellAt Method. . . . . . . . . . 195SelectReferredFootnotesAt Method . . . . . 195SetBackgroundColorAt Method . . . . . . 195SetBottomMarginAt Method . . . . . . . 196SetForegroundColorAt Method . . . . . . 196SetHAlignAt Method. . . . . . . . . . 196SetHDecDigitsAt Method . . . . . . . . 196SetLeftMarginAt Method . . . . . . . . 197SetNumericFormatAt method. . . . . . . 197SetNumericFormatAtWithDecimal method . . 197SetRightMarginAt Method. . . . . . . . 198SetTextColorAt Method. . . . . . . . . 198SetTextFontAt Method . . . . . . . . . 198SetTextHiddenAt Method . . . . . . . . 198SetTextSizeAt Method . . . . . . . . . 199SetTextStyleAt Method . . . . . . . . . 199SetTextUnderlinedAt Method. . . . . . . 199SetTopMarginAt Method . . . . . . . . 200SetVAlignAt Method. . . . . . . . . . 200SetValueAt Method . . . . . . . . . . 200ShowFootnotesAt Method . . . . . . . . 201SpssDimension Class . . . . . . . . . . . 201GetCategoryValueAt Method . . . . . . . 202GetCurrentCategory Method . . . . . . . 202GetDimensionName Method . . . . . . . 202GetFullDimensionLabel Method . . . . . . 202GetNumCategories Method. . . . . . . . 202HideLabel Method . . . . . . . . . . 203MoveToColumn Method. . . . . . . . . 203MoveToLayer Method . . . . . . . . . 203MoveToRow Method . . . . . . . . . . 203SetCurrentCategory Method . . . . . . . 203SetDimensionName Method . . . . . . . 204SpssFootnotes Class . . . . . . . . . . . 204ChangeMarkerToRegular Method. . . . . . 204ChangeMarkerToSpecial Method. . . . . . 204GetBackgroundColorAt Method . . . . . . 205GetBottomMarginAt Method . . . . . . . 205GetCount Method . . . . . . . . . . . 205GetForegroundColorAt Method . . . . . . 206GetHAlignAt Method . . . . . . . . . 206GetLeftMarginAt Method . . . . . . . . 206GetRightMarginAt Method . . . . . . . . 206GetTextColorAt Method . . . . . . . . . 207GetTextFontAt Method . . . . . . . . . 207GetTextHiddenAt Method . . . . . . . . 207GetTextSizeAt Method . . . . . . . . . 208GetTextStyleAt Method. . . . . . . . . 208GetTextUnderlinedAt Method . . . . . . . 208GetTopMarginAt Method . . . . . . . . 209GetVAlignAt Method. . . . . . . . . . 209GetValueAt Method . . . . . . . . . . 210RenumberFootnotes Method . . . . . . . 210SelectCellAt Method. . . . . . . . . . 210SetBackgroundColorAt Method . . . . . . 210SetBottomMarginAt Method . . . . . . . 211SetForegroundColorAt Method . . . . . . 211SetHAlignAt Method . . . . . . . . . . 211SetLeftMarginAt Method . . . . . . . . 212SetRightMarginAt Method. . . . . . . . 212SetTextColorAt Method. . . . . . . . . 212SetTextFontAt Method . . . . . . . . . 213SetTextHiddenAt Method . . . . . . . . 213SetTextSizeAt Method . . . . . . . . . 213SetTextStyleAt Method . . . . . . . . . 214SetTextUnderlinedAt Method. . . . . . . 214SetTopMarginAt Method . . . . . . . . 214SetVAlignAt Method. . . . . . . . . . 215SetValueAt Method . . . . . . . . . . 215SpssLabels Class . . . . . . . . . . . . 216BreakHere Method . . . . . . . . . . 219GetBackgroundColorAt Method . . . . . . 219GetBottomMarginAt Method . . . . . . . 219GetColumnLabelWidthAt Method . . . . . 219GetForegroundColorAt Method . . . . . . 220GetHAlignAt Method . . . . . . . . . 220GetLeftMarginAt Method . . . . . . . . 220GetNumColumns Method . . . . . . . . 220GetNumRows Method . . . . . . . . . 221GetReferredFootnotesAt Method. . . . . . 221GetRightMarginAt Method . . . . . . . . 221GetRowLabelWidthAt Method. . . . . . . 221GetTextColorAt Method . . . . . . . . . 222GetTextFontAt Method . . . . . . . . . 222GetTextHiddenAt Method . . . . . . . . 222GetTextSizeAt Method . . . . . . . . . 223GetTextStyleAt Method. . . . . . . . . 223GetTextUnderlinedAt Method . . . . . . . 223GetTextWidthAt Method . . . . . . . . 224GetTopMarginAt Method . . . . . . . . 224GetVAlignAt Method. . . . . . . . . . 224GetValueAt Method . . . . . . . . . . 225HideAllLabelsInDimensionAt Method . . . . 225HideFootnotesAt Method . . . . . . . . 225HideLabelsInDimensionAt Method . . . . . 225HideLabelsWithDataAt Method . . . . . . 226InsertBefore Method. . . . . . . . . . 226InsertNewAfter Method . . . . . . . . . 226InsertNewBefore Method . . . . . . . . 227InsertNewFootnoteAt Method . . . . . . . 227InsertSharedFootnoteAt Method . . . . . . 227KeepTogether Method . . . . . . . . . 228RemoveBreakHere Method . . . . . . . . 228Contents viiRemoveKeepTogether Method. . . . . . . 228SelectDataUnderLabelAt Method . . . . . . 229SelectLabelAt Method . . . . . . . . . 229SelectLabelDataAt Method. . . . . . . . 229SelectReferredFootnotesAt Method . . . . . 229SetBackgroundColorAt Method . . . . . . 230SetBottomMarginAt Method . . . . . . . 230SetColumnLabelWidthAt Method. . . . . . 230SetForegroundColorAt Method . . . . . . 231SetHAlignAt Method. . . . . . . . . . 231SetLeftMarginAt Method . . . . . . . . 231SetRightMarginAt Method. . . . . . . . 231SetRowLabelWidthAt Method . . . . . . . 232SetTextColorAt Method. . . . . . . . . 232SetTextFontAt Method . . . . . . . . . 232SetTextHiddenAt Method . . . . . . . . 233SetTextSizeAt Method . . . . . . . . . 233SetTextStyleAt Method . . . . . . . . . 233SetTextUnderlinedAt Method. . . . . . . 234SetTopMarginAt Method . . . . . . . . 234SetVAlignAt Method. . . . . . . . . . 234SetValueAt Method . . . . . . . . . . 235ShowAllLabelsAndDataInDimensionAt Method 235ShowAllLabelsInDimensionAt Method . . . . 235ShowFootnotesAt Method . . . . . . . . 235ShowHiddenDimensionLabelAt Method . . . 236Swap Method . . . . . . . . . . . . 236SpssLayerLabels Class . . . . . . . . . . 236GetBackgroundColorAt Method . . . . . . 237GetBottomMarginAt Method . . . . . . . 238GetForegroundColorAt Method . . . . . . 238GetHAlignAt Method . . . . . . . . . 238GetLeftMarginAt Method . . . . . . . . 238GetNumDimensions Method . . . . . . . 239GetNumLabelsWide Method . . . . . . . 239GetRightMarginAt Method . . . . . . . . 239GetTextColorAt Method . . . . . . . . . 239GetTextFontAt Method . . . . . . . . . 239GetTextHiddenAt Method . . . . . . . . 240GetTextSizeAt Method . . . . . . . . . 240GetTextStyleAt Method. . . . . . . . . 240GetTextUnderlinedAt Method . . . . . . . 241GetTopMarginAt Method . . . . . . . . 241GetVAlignAt Method. . . . . . . . . . 241GetValueAt Method . . . . . . . . . . 241HideFootnotesAt Method . . . . . . . . 242InsertNewFootnoteAt Method . . . . . . . 242InsertSharedFootnoteAt Method . . . . . . 242SelectLabelAt Method . . . . . . . . . 243SelectReferredFootnotesAt Method . . . . . 243SetBackgroundColorAt Method . . . . . . 243SetBottomMarginAt Method . . . . . . . 243SetForegroundColorAt Method . . . . . . 244SetHAlignAt Method. . . . . . . . . . 244SetLeftMarginAt Method . . . . . . . . 244SetRightMarginAt Method. . . . . . . . 244SetTextColorAt Method. . . . . . . . . 245SetTextFontAt Method . . . . . . . . . 245SetTextHiddenAt Method . . . . . . . . 245SetTextSizeAt Method . . . . . . . . . 245SetTextStyleAt Method . . . . . . . . . 246SetTextUnderlinedAt Method. . . . . . . 246SetTopMarginAt Method . . . . . . . . 246SetVAlignAt Method. . . . . . . . . . 246ShowFootnotesAt Method . . . . . . . . 247SpssPivotMgr Class . . . . . . . . . . . 247GetColumnDimension Method . . . . . . 247GetLayerDimension Method . . . . . . . 247GetNumColumnDimensions Method . . . . 248GetNumLayerDimensions Method . . . . . 248GetNumRowDimensions Method. . . . . . 248GetRowDimension Method. . . . . . . . 248MoveLayersToColumns Method . . . . . . 248MoveLayersToRows Method . . . . . . . 248TransposeRowsWithColumns Method . . . . 248Managing Remote Servers. . . . . . 249SpssServerConf Class. . . . . . . . . . . 249Connect Method . . . . . . . . . . . 250ConnectWithSavedPassword Method . . . . 250Disconnect Method . . . . . . . . . . 250GetDescription Method. . . . . . . . . 251GetServerName Method. . . . . . . . . 251GetServerPort Method . . . . . . . . . 251GetUserDomain Method. . . . . . . . . 251GetUserId Method. . . . . . . . . . . 251GetUseSSL Method . . . . . . . . . . 251IsDefaultServer Method . . . . . . . . . 251IsEqualTo Method . . . . . . . . . . . 252IsLocalServer Method . . . . . . . . . 252IsPasswordSaved Method . . . . . . . . 252SetDefaultServer Method . . . . . . . . 252SetDescription Method . . . . . . . . . 252SetPassword Method . . . . . . . . . . 252SetPasswordSaved Method . . . . . . . . 253SetServerName Method. . . . . . . . . 253SetServerPort Method . . . . . . . . . 253SetUserDomain Method . . . . . . . . . 253SetUserId Method . . . . . . . . . . . 253SetUseSSL Method . . . . . . . . . . 253SpssServerConfList Class . . . . . . . . . 254Add Method . . . . . . . . . . . . 254Clear Method . . . . . . . . . . . . 254Contains Method . . . . . . . . . . . 254GetItemAt Method . . . . . . . . . . 254Remove Method . . . . . . . . . . . 255RemoveItemAt Method. . . . . . . . . 255Size Method. . . . . . . . . . . . . 255SpssScriptContext Class . . . . . . 257GetOutputDoc Method . . . . . . . . . . 257GetOutputItem Method. . . . . . . . . . 257GetOutputItemIndex Method. . . . . . . . 257Part 3. Appendixes. . . . . . . . 259viii Python Reference Guide for IBM SPSS StatisticsAppendix A. Variable Format Types 261Appendix B. Setting Color Values. . . 263Appendix C. Export Options. . . . . 265Appendix D. String Description ofNumeric Formats. . . . . . . . . . 267Appendix E. Preference Options . . . 269Appendix F. Python ExtensionCommands for SPSS Statistics. . . . 273Notices. . . . . . . . . . . . . . 275Trademarks. . . . . . . . . . . . . . 277Index . . . . . . . . . . . . . . . 279Contents ixx Python Reference Guide for IBM SPSS StatisticsOverviewThe IBMSPSSStatistics - Integration Plug-in for Python provides two interfaces for programming withthe Python language within IBM SPSS Statistics on Windows, Linux, Mac OS, and for IBM SPSS StatisticsServer.Python Integration PackageThe Python Integration Package provides functions that operate on the IBM SPSS Statisticsprocessor, extending IBM SPSS Statistics command syntax with the full capabilities of the Pythonprogramming language. With this interface, you can access IBM SPSS Statistics variable dictionaryinformation, case data, and procedure output. You can submit command syntax to IBM SPSSStatistics for processing, create new variables and new cases in the active dataset, or create newdatasets. You can also create output in the form of pivot tables and text blocks, all from withinPython code.Scripting FacilityThe Scripting Facility provides Python functions that operate on user interface and output objects.With this interface, you can customize pivot tables, and export items such as charts and tables invarious formats. You can also start IBM SPSS Statistics dialog boxes, and manage connections toinstances of IBM SPSS Statistics Server, all from within Python code.The IBM SPSS Statistics - Integration Plug-in for Python is included with IBM SPSS Statistics - Essentialsfor Python, which is installed by default with your IBM SPSS Statistics product. Essentials for Python alsoincludes Python version 2.7 on all supported operating systems (Windows, Linux, Mac OS, and UNIX forIBM SPSS Statistics Server) and a set of extension commands that are implemented in Python thatprovide capabilities beyond what is available with built-in SPSS Statistics procedures.By default, the Integration Plug-in for Python uses the version of Python 2.7 that is installed with yourIBM SPSS Statistics product (as part of Essentials for Python). It is in the Python directory under thedirectory where SPSS Statistics is installed. You can specify to use a different installation of Python 2.7 onthe File Locations tab on the Options dialog (Edit>Options). In distributed analysis mode (requires IBMSPSS Statistics Server), the Python location on the remote server is set from the IBM SPSS StatisticsAdministration Console. Contact your system administrator for assistance.Note: The locations for extension commands that are listed in the output from the SHOW EXTPATHScommand are added to the Python search path when you are accessing Python from within IBM SPSSStatistics. If you develop your own Python modules for use with IBM SPSS Statistics on your computerthen you can store your modules in one of those locations.Related information:Appendix F, Python Extension Commands for SPSS Statistics, on page 273xixii Python Reference Guide for IBM SPSS StatisticsPart 1. Python Integration Package for IBM SPSS Statistics12 Python Reference Guide for IBM SPSS StatisticsIntroduction to Python ProgramsThe PythonIntegration Package for IBM SPSS Statistics allows you to create Python programs thatcontrol the flow of command syntax jobs, read and write data, and create custom procedures thatgenerate their own pivot table output. This feature requires the IBM SPSS Statistics - Integration Plug-infor Python, which is installed by default with your IBM SPSS Statistics product.A companion interface is available for creating Python scripts that operate on the IBM SPSS Statisticsuser interface and manipulate output objects. See the topic Introduction to Python Scripts on page 95for more information.Python programming features described here are available insideBEGINPROGRAM-ENDPROGRAM programblocks in command syntax. A program block provides access to all the functionality of the Pythonprogramming language, including the functions specific to IBM SPSS Statistics and provided in thePython Integration Package for IBM SPSS Statistics. You can use program blocks to combine theprogrammability features of Python with all the capabilities of IBM SPSS Statistics by building strings ofcommand syntax that are then executed by IBM SPSS Statistics.You can also run IBM SPSS Statistics from an external Python process, such as a Python IDE or thePython interpreter. See the topic Running IBM SPSS Statistics from an External Python Process on page9 for more information.Within a program block, Python is in control, and it knows nothing about IBM SPSS Statistics commands.When the Python Integration Package for IBM SPSS Statistics is loaded, Python knows about thefunctions provided in the package, but standard IBM SPSS Statistics commands are basically invalidwithin a program block. For example:BEGINPROGRAMPYTHON.FREQUENCIESVARIABLES=var1,var2,var3.ENDPROGRAM.will generate an error, because FREQUENCIES is not recognized by Python. But since the goal of a programblock is typically to generate some command syntax that IBM SPSS Statistics can understand, there mustbe a way to specify command syntax within a program block. This is done by expressing syntaxcommands, or parts of commands, as character strings, as in:spss.Submit("FREQUENCIESVARIABLES=var1,var2,var3.")The real power of program blocks comes from the ability to dynamically build strings of commandsyntax, as in:BEGINPROGRAMPYTHON.importspssstring1="DESCRIPTIVESVARIABLES="N=spss.GetVariableCount()scaleVarList=[]foriinxrange(N):ifspss.GetVariableMeasurementLevel(i)==scale:scaleVarList.append(spss.GetVariableName(i))string2="."spss.Submit([string1,.join(scaleVarList),string2])ENDPROGRAM.v spss.GetVariableCount returns the number of variables in the active dataset.v ifspss.GetVariableMeasurementLevel(i)=="scale" is true only for variables with a scalemeasurement level.v scaleVarList.append(spss.GetVariableName(i)) builds a list of variable names that includes onlythose variables with a scale measurement level.v spss.Submit submits a DESCRIPTIVES command to IBM SPSS Statistics that looks something like this: Copyright IBM Corporation 1989, 2013 3DESCRIPTIVESVARIABLES=scalevar1scalevar2scalevar3...etc..Working with Python Program BlocksUseSETPRINTBACKONMPRINTONtodisplaythesyntaxgeneratedbyprogramblocks.ExampleSETPRINTBACKONMPRINTON.GETFILE=/examples/data/Employeedata.sav.BEGINPROGRAMPYTHON.importspssscaleVarList=[]catVarList=[]varcount=spss.GetVariableCount()foriinxrange(varcount):ifspss.GetVariableMeasurementLevel(i)==scale:scaleVarList.append(spss.GetVariableName(i))else:catVarList.append(spss.GetVariableName(i))spss.Submit("""FREQUENCIES/VARIABLES=%s.DESCRIPTIVES/VARIABLES=%s."""%(.join(catVarList),.join(scaleVarList)))ENDPROGRAM.The generated command syntax is displayed in the log in the IBM SPSS Statistics Viewer:225M> FREQUENCIES226M> /VARIABLES=gendereducjobcatminority.227M> DESCRIPTIVES228M> /VARIABLES=idbdatesalarysalbeginjobtimeprevexp.Basic Specification for a Python Program BlockThe basic specification for a Python program block isBEGINPROGRAMPYTHON (the keywordPYTHON can beomitted) followed by one or more Python statements, followed byEND PROGRAM.Note: The Python function sys.exit() is not supported for use within a program block.v The first program block in a session should start with the Python function import spss, which importsthe spss module, providing access to the functions in the Python Integration Package for IBM SPSSStatistics. See the topic Python Functions and Classes on page 15 for more information.v Subsequent program blocks in the same session do not require import spss, and it is silently ignored ifthe module has already been imported.ExampleDATALISTFREE/var1.BEGINDATA1ENDDATA.DATASETNAMEFile1.BEGINPROGRAMPYTHON.importspssFile1N=spss.GetVariableCount()ENDPROGRAM.DATALISTFREE/var1var2var3.BEGINDATA123ENDDATA.DATASETNAMEFile2.BEGINPROGRAMPYTHON.File2N=spss.GetVariableCount()ifFile2N>File1N:message="File2hasmorevariablesthanFile1."elifFile1N>File2N:message="File1hasmorevariablesthanFile2."4 Python Reference Guide for IBM SPSS Statisticselse:message="Bothfileshavethesamenumberofvariables."printmessageENDPROGRAM.v The first program block contains the import spss statement. This statement is not required in thesecond program block.v The first program block defines a programmatic variable, File1N, with a value set to the number ofvariables in the active dataset.v Prior to the second program block, a different dataset becomes the active dataset, and the secondprogram block defines a programmatic variable, File2N, with a value set to the number of variables inthat dataset.v Since the value of File1N persists from the first program block, the two variable counts can becompared in the second program block.Syntax Rulesv Within a program block, only statements recognized by the specified programming language areallowed.v Command syntax generated within a program block must follow interactive syntax rules. See the topicfor more information.v Within a program block, each line should not exceed 251 bytes (although syntax generated by thoselines can be longer).v With the IBM SPSS Statistics Batch Facility (available only with IBM SPSS Statistics Server), use the -iswitch when submitting command files that contain program blocks. All command syntax (not just theprogram blocks) in the file must adhere to interactive syntax rules.Within a program block, the programming language is in control, and the syntax rules for thatprogramming language apply. Command syntax generated from within program blocks must alwaysfollow interactive syntax rules. For most practical purposes this means command strings you build in aprogramming block must contain a period (.) at the end of each command.Scope and Limitationsv Programmatic variables created in a program block cannot be used outside of program blocks.v Program blocks cannot be contained within DEFINE-!ENDDEFINE macro definitions.v Program blocks can be contained in command syntax files run via the INSERT command, with thedefault SYNTAX=INTERACTIVE setting.v Program blocks cannot be contained within command syntax files run via the INCLUDE command.v Python variables specified in a given program block persist to subsequent program blocks.v Python programs (.py, .pyc) utilizing the spss module cannot be run as autoscripts, nor are theyintended to be run from Utilities>Run Script.More information about Python programs and Python scripts is available from the IBM SPSS StatisticsHelp system, and accessed from Core System>Scripting Facility.Nested Program BlocksFrom within Python, you can submit command syntax containing a BEGIN PROGRAM block, thus allowingyou to nest program blocks. This can be done by including the nested program block in a separatecommand syntax file and submitting an INSERT command to read in the block. It can also be done bysubmitting the nested program block from within a user-defined Python function.Example: Nesting Program Blocks Using the INSERT Commandimportspssspss.Submit("INSERTFILE=/myprograms/nested_block.sps.")Introduction to Python Programs 5The file /myprograms/nested_block.sps would contain aBEGINPROGRAM block, as in:BEGINPROGRAMPYTHON.importspss

ENDPROGRAM.Note: You cannot import a Python module containing code that nests a program block, such as the abovecode that uses the INSERT command to insert a file containing a program block. If you wish toencapsulate nested program blocks in a Python module that can be imported, then embed the nestingcode in a user-defined function as shown in the following example.Example: Nesting Program Blocks With a User-Defined Python Functionimportspss,myfuncsmyfuncs.demo()v myfuncs is a user-defined Python module containing the function (demo) that will submit the nestedprogram block.A Python module is simply a text file containing Python definitions and statements. You can create amodule with a Python IDE, or with any text editor, by saving a file with an extension of .py. The nameof the file, without the .py extension, is then the name of the module.v The import statement includes myfuncs so that it is loaded along with the spss module. To be sure thatPython can find your module, you may want to save it to your Python "site-packages" directory,typically /Python27/Lib/site-packages.v The code myfuncs.demo() calls the function demo in the myfuncs module.Following is a sample of the contents of myfuncs.importspssdefdemo():spss.Submit("""BEGINPROGRAMPYTHON.

ENDPROGRAM.""")v The sample myfuncs module includes an import spss statement. This is necessary since a function inthe module makes use of a function from the spss module--specifically, the Submit function.v The nested program block is contained within a Python triple-quoted string. Triple-quoted stringsallow you to specify a block of commands on multiple lines, resembling the way you might normallywrite command syntax.v Notice thatspss.Submit is indented but theBEGINPROGRAM block is not. Python statements that formthe body of a user-defined Python function must be indented. The level of indentation is arbitrary butmust be the same for all statements in the function body. The BEGIN PROGRAM block is passed as a stringargument to the Submit function and is processed by IBM SPSS Statistics as a block of Pythonstatements. Python statements are not indented unless they are part of a group of statements, as in afunction or class definition, a conditional expression, or a looping structure.Notesv You can nest program blocks within nested program blocks, up to five levels of nesting.v Python variables specified in a nested program block are local to that block unless they are specified asglobal variables. In addition, Python variables specified in a program block that invokes a nested blockcan be read, but not modified, in the nested block.v Nested program blocks are not restricted to being Python program blocks, but you can only submit anested block from Python. For example, you can nest an R program block in a Python program block,but you cannot nest a Python program block in an R program block.v If a Submit function containing a triple quoted string nests a Python program block containing anothertriple quoted string, use a different type of triple quotes in the nested block. For example, if the outerblock uses triple double quotes, then use triple single quotes in the nested block.6 Python Reference Guide for IBM SPSS StatisticsUnicode ModeWhen IBM SPSS Statistics is in Unicode mode (controlled by the UNICODE subcommand of the SETcommand) the following conversions are automatically done when passing and receiving strings throughthe functions available with the spss module:v Strings received by Python from IBM SPSS Statistics are converted from UTF-8 to Python Unicode,which is UTF-16.v Strings passed from Python to IBM SPSS Statistics are converted from UTF-16 to UTF-8.Note: Changing the locale and/or the unicode setting during an OMS request may result in incorrectlytranscoded text.Command Syntax FilesSpecial care must be taken when working in Unicode mode with command syntax files. Specifically,Python string literals used in command syntax files need to be explicitly expressed as UTF-16 strings.This is best done by using the u() function from the spssaux module (installed with IBM SPSS Statistics -Essentials for Python). The function has the following behavior:v If IBM SPSS Statistics is in Unicode mode, the input string is converted to UTF-16.v If IBM SPSS Statistics is not in Unicode mode, the input string is returned unchanged.Note: If the string literals in a command syntax file only consist of plain roman characters (7-bit ascii), theu() function is not needed.The following example demonstrates some of this behavior and the usage of the u() function.setunicodeonlocale=english.BEGINPROGRAM.importspss,spssauxfromspssauximportuliteral="bc"try:print"literalwithoutconversion:",literalexcept:print"cantprintliteral"try:print"literalconvertedtoutf-16:",u(literal)except:print"cantprintliteral"ENDPROGRAM.Following are the results:literalwithoutconversion:cantprintliteralliteralconvertedtoutf-16:bcTruncating Unicode StringsWhen working in Unicode mode, use the truncatestring function from the spssaux module (installedwith IBM SPSS Statistics - Essentials for Python) to correctly truncate a string to a specified maximumlength in bytes. This is especially useful for truncating strings to be used as IBM SPSS Statistics variablenames, which have a maximum allowed length of 64 bytes.The truncatestring function takes two arguments--the string to truncate, and the maximum number ofbytes, which is optional and defaults to 64. For example:importspss,spssauxnewstring=spssaux.truncatestring(string,8)Python Syntax RulesWithin a Python program block, only statements and functions recognized by Python are allowed. Pythonsyntax rules differ from IBM SPSS Statistics command syntax rules in a number of ways:Introduction to Python Programs 7Python is case-sensitive. This includes variable names, function names, and pretty much anything elseyou can think of. A variable name of myvariable is not the same as MyVariable, and the functionspss.GetVariableCount cannot be written as SPSS.getvariablecount.Python uses UNIX-style path specifications, with forward slashes. This applies even for IBM SPSSStatistics command syntax generated within a Python program block. For example:spss.Submit("GETFILE/data/somedata.sav.")Alternatively, you can escape each backslash with another backslash, as in:spss.Submit("GETFILE\\data\\somedata.sav.")There is no command terminator in Python, and continuation lines come in two flavors:v Implicit. Expressions enclosed in parentheses, square brackets, or curly braces can continue acrossmultiple lines without any continuation character. The expression continues implicitly until the closingcharacter for the expression.v Explicit. All other expression require a backslash at the end of each line to explicitly denotecontinuation.Line indentation indicates grouping of statements. Groups of statements contained in conditionalprocessing and looping structures are identified by indentation, as is the body of a user-defined Pythonfunction. There is no statement or character that indicates the end of the structure. Instead, theindentation level of the statements defines the structure, as in:foriinxrange(varcount):ifspss.GetVariableMeasurementLevel(i)=="scale":ScaleVarList=ScaleVarList+""+spss.GetVariableName(i)else:CatVarList=CatVarList+""+spss.GetVariableName(i)printCatVarListNote: You should avoid the use of tab characters in Python code withinBEGINPROGRAM-ENDPROGRAMblocks. For line indentation, use spaces.Working with Multiple Versions of IBM SPSS StatisticsFor versions 16.0 to 21.0, special considerations apply when multiple versions of the IBM SPSS Statistics -Integration Plug-in for Python (each associated with a major version of IBM SPSS Statistics, such as 20 or21) are installed on your computer. These considerations do not apply to versions 14.0 or 15.0 or forversions 22.0 and higher.Running Python Programs from Within IBM SPSS StatisticsBy default, Python programs run from within the last installed version of IBM SPSS Statistics willautomatically use the appropriate version of the plug-in. To run Python programs from within a differentversion of IBM SPSS Statistics, use the spss.SetDefaultPlugInVersion function to set the default to adifferent version (the setting persists across sessions). You can then run Python programs from within theother version. If you are attempting to change the default version from 16.0 to 17.0, additionalconfiguration is required; please see the Notes below.Running Python Programs from an External Python ProcessWhen you are driving the IBM SPSS Statistics backend from a separate Python process, such as thePython interpreter or a Python IDE, the plug-in will drive the version of the IBM SPSS Statistics backendthat matches the default plug-in version specified for that version of Python. Unless you change it, thedefault plug-in version for a given version of Python (such as Python 2.6) is the last one installed. Youcan view the default version using the spss.GetDefaultPlugInVersion function and you can change thedefault version using the spss.SetDefaultPlugInVersion function. The setting persists across sessions. Ifyou are attempting to change the default version from 16.0 to 17.0 please see the Notes below.8 Python Reference Guide for IBM SPSS StatisticsNote:v If you are using the spss.SetDefaultPlugInVersion function to change the default from version 16.0 toversion 17.0, you should also manually modify the file SpssClient.pth located in the Python 2.5site-packages directory. Change the order of entries in the file so that the first line is SpssClient170.Windows. The site-packages directory is located in the Lib directory under the Python 2.5 installationdirectoryfor example, C:\Python25\Lib\site-packages.Mac OS X 10.4 (Tiger). The site-packages directory is located at /Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages.Mac OS X 10.5 (Leopard). The site-packages directory is typically located at /Library/Python/2.5/site-packages.Linux and UNIX Server. The site-packages directory is located in the /lib/python2.5/ directory under thePython 2.5 installation directoryfor example, /usr/local/python25/lib/python2.5/site-packages.v Beginning with version 15.0, a restructuring of the IBM SPSS Statistics - Integration Plug-in for Pythoninstallation directory and changes to some class structures may affect Python code written for anearlier version and used with a 15.0 or higher version. Specifically, the type of an object, as given bythe Python type function, may return a different result. For example:cur=spss.Cursor()printtype(cur)will return spss.cursors.Cursor when run with version 14.0, spss.spss150.cursors.ReadCursor whenrun with version 15.0, and spss.cursors.ReadCursor when run with a version higher than 15.0.Python and IBM SPSS Statistics Working DirectoriesWhen running Python code that is within aBEGINPROGRAM-ENDPROGRAM block and that contains relativepaths in file specifications, you will need to understand the notions of working directories, both forPython and IBM SPSS Statistics. You may want to avoid the subtleties involved with working directoriesby avoiding the use of relative paths and using full paths for file specifications.v Relative paths used for file specifications in command syntax submitted from Python (withspss.Submit) are relative to the IBM SPSS Statistics backend working directory. The IBM SPSS Statisticsbackend working directory determines the full path used for file specifications in command syntax inthe case where only a relative path is provided. It can be changed with the CD command, but is notaffected by actions involving the file open dialogs, and it is private to the IBM SPSS Statistics backend.v Relative paths used when reading and writing files with built-in Python functions--such as open--arerelative to the Python current working directory. You can get the Python current working directoryfrom the getcwd function in the os module.Running IBM SPSS Statistics from an External Python ProcessYou can run Python programs utilizing the spss module from any external Python process, such as aPython IDE or the Python interpreter. In this mode, the Python program starts up a new instance of theIBM SPSS Statistics processor without an associated instance of the IBM SPSS Statistics client. You can usethis mode to debug your Python programs using the Python IDE of your choice.To drive the IBM SPSS Statistics processor from a Python IDE, simply include an import spss statementin the IDE's code window. You can follow the import statement with calls to any of the functions in thespss module, just like with program blocks in command syntax jobs, but you do not need to wrap yourPython code inBEGINPROGRAM-ENDPROGRAM statements. Some initial configuration may be required asdescribed in the following sections.Introduction to Python Programs 9Windows UsersYou can start IDLE (the default IDE provided with Python) from All Programs > IBM SPSS Statistics >Python 2.7 for IBM SPSS Statistics 22 > IDLE(PythonGUI). This action starts IDLE from the Pythonlocation that is specified on the File Locations tab in the Options dialog. You can then use import spss tostart driving the IBM SPSS Statistics processor.If you do not use IDLE to drive IBM SPSS Statistics, then you must modify the Python search path toadd the path to the spss module. You can add to the Python search path by modifying (or creating) thesitecustomize.py module for the installation of Python 2.7 you want to use. The sitecustomize.pymodule, if it exists, is in the \Lib\site-packages directory, where is theinstallation location of Python 2.7; for example, C:\Python27\Lib\site-packages. If it does not exist thencreate it in that location.Add the following lines to sitecustomize.py:importsyssys.path.insert(0,r\Python\Lib\site-packages)In the preceding expression, is the installation location of IBM SPSS Statistics; for example,C:\ProgramFiles\IBM\SPSS\Statistics\22.Linux UsersThe statisticspython script, in the bin directory under the location where IBM SPSS Statistics isinstalled, starts the Python interpreter from the Python location that is specified on the File Locations tabin the Options dialog. You can then use import spss to start driving the IBM SPSS Statistics processor.If you choose not to use this script, then you must modify the Python search path to add the path to thespss module. You can add to the Python search path by modifying (or creating) the sitecustomize.pymodule for the installation of Python 2.7 you want to use. The sitecustomize.py module, if it exists, is inthe /lib/python2.7/site-packages directory, where is the installationlocation of Python 2.7. If it does not exist then create it in that location.Add the following lines to sitecustomize.py:importsyssys.path.insert(0,/Python/lib/python2.7/site-packages)In the preceding expression, is the installation location of IBM SPSS Statistics; for example,/opt/IBM/SPSS/Statistics/22.You must also modify the LD_LIBRARY_PATH environment variable as follows:exportLD_LIBRARY_PATH=/lib:/lib:$LD_LIBRARY_PATHIn the preceding expression, is the location of the installation of Python 2.7 you want touse. For reference, for the version of Python 2.7 that is installed with IBM SPSS Statistics, is /Python.Mac UsersTo drive the IBM SPSS Statistics processor from an external Python process on Mac, start the Python forSPSS Statistics application, which is in the directory where IBM SPSS Statistics is installed. Theapplication starts IDLE from the Python location that is specified on the File Locations tab in the Optionsdialog. You can then use import spss to start driving the IBM SPSS Statistics processor.If you choose not to use the Python for SPSS Statistics application, then you must modify the Pythonsearch path to add the path to the spss module. You can add to the Python search path by modifying (or10 Python Reference Guide for IBM SPSS Statisticscreating) the sitecustomize.py module for the installation of Python 2.7 you want to use. Thesitecustomize.py module, if it exists, is in the /lib/python2.7/site-packages directory,where is the installation location of Python 2.7. If it does not exist then create it in thatlocation.Add the following lines to sitecustomize.py:importsyssys.path.insert(0,/Python/lib/python2.7/site-packages)In the preceding expression, is the location of the IBM SPSS Statistics application bundle;for example, /Applications/IBM/SPSS/Statistics/22.You must also modify environment variables as follows:exportDYLD_LIBRARY_PATH=/lib:/Library/Frameworks/Sentinel.framework/Versions/A:/Library/Frameworks/SuperPro.framework/Versions/AexportPYTHONHOME=In the preceding expression, is the location of the Contents folder in the IBM SPSS Statisticsapplication bundle, and is given by /SPSSStatistics.app/Contents. is thelocation of the installation of Python 2.7 you want to use. For reference, for the version of Python 2.7 thatis installed with IBM SPSS Statistics, is /Python.Localizing Output from Python ProgramsYou can localize output, such as messages and pivot table strings, from extension commandsimplemented in Python. The localization process consists of the following steps:1. Modifying the Python implementation code to identify translatable strings2. Extracting translatable text from the implementation code using standard Python tools3. Preparing a translated file of strings for each target language4. Installing the translation files along with the extension commandThe process described here assumes use of the Python extension module, which is installed with IBMSPSS Statistics - Essentials for Python.Notesv When running an extension command from within IBM SPSS Statistics, the language for extensioncommand output will be automatically synchronized with the IBM SPSS Statistics output language(OLANG). When running an extension command from an external Python process, such as a Python IDE,you can set the output language by submitting a SET OLANG command when IBM SPSS Statistics isstarted. If no translation for an item is available for the output language, the untranslated string will beused.v Messages produced by the extension module, such as error messages for violation of the specificationsin the Syntax definition, are automatically produced in the current output language. Exceptions raisedin the extension command implementation code are automatically converted to a Warnings pivot table.v Translation of dialog boxes built with the Custom Dialog Builder is a separate process, but translatorsshould ensure that the dialog and extension command translations are consistent.Additional ResourcesExamples of extension commands implemented in Python with localized output are included with IBMSPSS Statistics - Essentials for Python. The Python modules for these examples are located in theextensions directory under the IBM SPSS Statistics installation directory. If you have specified alternateIntroduction to Python Programs 11locations for extension commands with the SPSS_EXTENSIONS_PATH environment variable then thePython modules will be located in the first writable location in that variable instead of in the extensionsdirectory.Information on creating extension commands is also available from the following sources:v The article "Writing IBM SPSS Statistics Extension Commands", available from the SPSS Community athttp://www.ibm.com/developerworks/spssdevcentral.v The chapter on Extension Commands in Programming and Data Management for IBM SPSS Statistics ,available in PDF from the Articles page at http://www.ibm.com/developerworks/spssdevcentral.Modifying the Python codeFirst, ensure that the text to be translated is in a reasonable form for translation.v Do not build up text by combining fragments of text in code. This makes it impossible to rearrange thetext according to the grammar of the target languages and makes it difficult for translators tounderstand the context of the strings.v Avoid using multiple parameters in a string. Translators may need to change the parameter order.v Avoid the use of abbreviations and colloquialisms that are difficult to translate.Enclose each translatable string in a call to the underscore function "_". For example:_("Filenotfound:%s")%filespecThe _ function will fetch the translation, if available, when the statement containing the string isexecuted. The following limitations apply:v Never pass an empty string as the argument to _, i.e., _(""). This will damage the translationmechanism.v Do not use the underscore function in static text such as class variables. The _ function is defineddynamically.v The _ function, as defined in the extension module, always returns Unicode text even if IBM SPSSStatistics is running in code page mode. If there are text parameters in the string as in the exampleabove, the parameter should be in Unicode. The automatic conversion used in the parametersubstitution logic will fail if the parameter text contains any extended characters. One way to resolvethis is as follows, assuming that the locale module has been imported.ifnotisinstance(filespec,unicode):filespec=unicode(filespec,locale.getlocale()[1])_("Filenotfound:%s")%filespecNote: There is a conflict between the definition of the _ function as used by the Python modules(pygettext and gettext) that handle translations, and the automatic assignment of interactively generatedexpression values to the variable _. In order to resolve this, the translation initialization code in theextension module disables this assignment.Calls to the spss.StartProcedure function (or the spss.Procedure class) should use the formspss.StartProcedure(procedureName,omsIdentifier) where procedureName is the translatable nameassociated with output from the procedure and omsIdentifier is the language invariant OMS commandidentifier associated with the procedure. For example:spss.StartProcedure(_("Demo"),"demoId")Extracting translatable textThe Python implementation code is never modified by the translators. Translation is accomplished byextracting the translatable text from the code files and then creating separate files containing thetranslated text, one file for each language. The _ function uses compiled versions of these files.12 Python Reference Guide for IBM SPSS StatisticsThe standard Python distribution includes pygettext.py, which is a command line script that extractsstrings marked as translatable (i.e., strings wrapped in the _ function) and saves them to a .pot file. Runpygettext.py on the implementation code, and specify the name of the implementing Python module(the module containing the Run function) as the name of the output file, but with the extension .pot. If theimplementation uses multiple Python files, the .pot files for each should be combined into one under thename of the main implementing module (the module containing the Run function).v Change the charset value, in the msgstr field corresponding to msgid "", to utf-8.v A pot file includes one msgid field with the value "", with an associated msgstr field containingmetadata. There must be only one of these.v Optionally, update the generated title and organization comments.Documentation for pygettext.py is available from the topic on the gettext module in the Python helpsystem.Translating the pot fileTranslators enter the translation of each msgid into the corresponding msgstr field and save the result as afile with the same name as the pot file but with the extension .po. There will be one po file for each targetlanguage.v po files should be saved in Unicode utf-8 encoding.v po files should not have a BOM (Byte Order Mark) at the start of the file.v If a msgstr contains an embedded double quote character (x22), precede it with a backslash (\). as in:msgstr"Hesaid,\"Wow\",whenhesawtheR-squared"v msgid and msgstr entries can have multiple lines. Enclose each line in double quotes.Each translated po file is compiled into a binary format by running msgfmt.py from the standard Pythondistribution, giving the output the same name as the po file but with an extension of .mo.Installing the mo filesWhen installed, the mo files should reside in the following directory structure:lang//LC_MESSAGES/.mov is the name of the extension command in upper case with any spaces replaced withunderscores, and is the same as the name of the Python implementation module. Note that the mo fileshave the same name for all languages.v is the identifier for a particular language. Identifiers for the languages supportedby IBM SPSS Statistics are shown in the section on Language Identifiers at the end of this topic.For example, if the extension command is named MYORG MYSTAT then an mo file for French should bestored in lang/fr/LC_MESSAGES/MYORG_MYSTAT.mo.Manually installing translation filesIf you are manually installing an extension command and associated translation files, then the langdirectory containing the translation files should be installed in the directory under thedirectory where the Python implementation module is installed.For example, if the extension command is named MYORG MYSTAT and the associated Pythonimplementation module (MYORG_MYSTAT.py) is located in the extensions directory (under the locationwhere IBM SPSS Statistics is installed), then the lang directory should reside under extensions/MYORG_MYSTAT.Introduction to Python Programs 13Using the example of a French translation discussed above, an mo file for French would be stored inextensions/MYORG_MYSTAT/lang/fr/LC_MESSAGES/MYORG_MYSTAT.mo.Deploying translation files to other usersIf you are localizing output for a custom dialog or extension command that you intend to distribute toother users, then you should create an extension bundle (requires IBM SPSS Statistics version 18 orhigher) to package your translation files with your custom components. Specifically, you add the langdirectory containing your compiled translation files (mo files) to the extension bundle during the creationof the bundle (from the Translation Catalogues Folder field on the Optional tab of the Create ExtensionBundle dialog). When an end user installs the extension bundle, the directory containing the translationfiles is installed in the extensions/ directory under the IBM SPSS Statisticsinstallation location, and where is the name of the extension bundle with spacesreplaced by underscores. Note: An extension bundle that includes translation files for an extensioncommand should have the same name as the extension command.v If the SPSS_EXTENSIONS_PATH environment variable has been set, then the extensions directory (inextensions/) is replaced by the first writable directory in the environmentvariable.v Information on creating extension bundles is available from the Help system, under CoreSystem>Utilities>Working with Extension Bundles.Language Identifiersde. Germanen. Englishes. Spanishfr. Frenchit. Italianja. Japaneseko. Koreanpl. Polishpt_BR. Brazilian Portugueseru. Russianzh_CN. Simplified Chinesezh_TW. Traditional Chinese14 Python Reference Guide for IBM SPSS StatisticsPython Functions and ClassesThe Python Integration Package for IBM SPSS Statistics contains functions and classes that facilitate theprocess of using Python programming features with IBM SPSS Statistics, including those that:Build and run command syntaxv spss.SubmitGet information about data files in the current IBM SPSS Statistics sessionv spss.GetCaseCountv spss.GetDataFileAttributesv spss.GetFileHandlesv spss.GetMultiResponseSetv spss.GetSplitVariableNamesv spss.GetVarAttributesv spss.GetVariableCountv spss.GetVariableFormatv spss.GetVariableLabelv spss.GetVariableMeasurementLevelv spss.GetVariableNamev spss.GetVariableTypev spss.GetVarMissingValuesv spss.GetWeightVarGet data, add new variables, and append cases to the active datasetv spss.CursorAccess and manage multiple datasetsv spss.ActiveDatasetv spss.Datasetv spss.GetDatasetsv spss.GetFileHandlesv spss.IsActivev spss.SetActiveGet output resultsv spss.EvaluateXPathv spss.GetXmlUtf16Create custom pivot tables and text blocksv spss.BasePivotTablev spss.TextBlockCreate macro variablesv spss.SetMacroValue Copyright IBM Corporation 1989, 2013 15Get error informationv spss.GetLastErrorLevelv spss.GetLastErrorMessageManage multiple versions of the IBM SPSS Statistics - Integration Plug-in for Pythonv spss.GetDefaultPlugInVersionv spss.SetDefaultPlugInVersionv spss.ShowInstalledPlugInVersionsLocale and Output Language Settingsv spss.GetSPSSLocalev spss.SetOutputLanguageBrief descriptions of each function are available using the Python help function, as in:BEGINPROGRAM.importspsshelp(spss.Submit)ENDPROGRAM.spss.ActiveDataset Functionspss.ActiveDataset(). Returns the name of the active dataset.v If the active dataset is unnamed, '*' is returned.Exampleimportspssname=spss.ActiveDataset()spss.AddProcedureFootnotes Functionspss.AddProcedureFootnotes(footnote). Adds a footnote to all tables generated by a procedure. The argumentfootnote is a string specifying the footnote.v The AddProcedureFootnotes function can only be used within a StartProcedure-EndProcedure block orwithin a custom procedure class based on the spss.BaseProcedure class.Exampleimportspssspss.StartProcedure("mycompany.com.demoProc")spss.AddProcedureFootnotes("Afootnote")table=spss.BasePivotTable("TableTitle","OMStablesubtype")table.SimplePivotTable(cells=[1,2,3,4])spss.EndProcedure()spss.BasePivotTable Classspss.BasePivotTable(title,templateName,outline,isSplit,caption). Provides the ability to create custom pivottables that can be displayed in the IBM SPSS Statistics Viewer or written to an external file using the IBM SPSSStatistics Output Management System.v The argument title is a string that specifies the title that appears with the table. Each table associatedwith a set of output (as specified in a StartProcedure-EndProcedure block) should have a unique title.Multiple tables within a given procedure can, however, have the same value of the title argument aslong as they have different values of the outline argument.v The argument templateName is a string that specifies the OMS (Output Management System) tablesubtype for this table. It must begin with a letter and have a maximum of 64 characters. Unless you are16 Python Reference Guide for IBM SPSS Statisticsrouting this pivot table with OMS, you will not need to keep track of this value, although you do haveto provide a value that meets the stated requirements.Note: Specifying "Warnings" for templateName will generate an IBM SPSS Statistics Warnings table.Unless you want to generate an IBM SPSS Statistics Warnings table, you should avoid specifying"Warnings" for templateName. See the topic Creating a Warnings Table on page 36 for moreinformation.v The optional argument outline is a string that specifies a title, for the pivot table, that appears in theoutline pane of the Viewer. The item for the table itself will be placed one level deeper than the itemfor the outline title. If omitted, the Viewer item for the table will be placed one level deeper than theroot item for the output containing the table.v The optional Boolean argument isSplit specifies whether to enable split processing when creating pivottables from data that have splits. By default, split processing is enabled. To disable split processing forpivot tables, specify isSplit=False. If you are creating a pivot table from data that has splits and youwant separate results displayed for each split group, you will want to make use of thespss.SplitChange function. In the absence of calls to spss.SplitChange, isSplit has no effect.v The optional argument caption is a string that specifies a table caption.An instance of the BasePivotTable class can only be used within a StartProcedure-EndProcedure block orwithin a custom procedure class based on the spss.BaseProcedure class. For an example of creating apivot table using spss.StartProcedure-spss.EndProcedure, see Creating Pivot Tables with theSimplePivotTable Method on page 18. For an example of creating a pivot table using a class based onthe spss.BaseProcedure class, see spss.BaseProcedure Class on page 37.The figure below shows the basic structural components of a pivot table. Pivot tables consists of one ormore dimensions, each of which can be of the type row, column, or layer. In this example, there is onedimension of each type. Each dimension contains a set of categories that label the elements of thedimension--for instance, row labels for a row dimension. A layer dimension allows you to display aseparate two-dimensional table for each category in the layered dimension--for example, a separate tablefor each value of minority classification, as shown here. When layers are present, the pivot table can bethought of as stacked in layers, with only the top layer visible.Each cell in the table can be specified by a combination of category values. In the example shown here,the indicated cell is specified by a category value of Male for the Gender dimension, Custodial for theEmployment Category dimension, and No for the Minority Classification dimension.Figure 1. Pivot table structurePython Functions and Classes 17Creating Pivot Tables with the SimplePivotTable MethodFor creating a pivot table with a single row dimension and a single column dimension, theBasePivotTable class provides the SimplePivotTable method. The arguments to the method provide thedimensions, categories, and cell values. No other methods are necessary in order to create the tablestructure and populate the cells. If you require more functionality than the SimplePivotTable methodprovides, there are a variety of methods to create the table structure and populate the cells. See the topicGeneral Approach to Creating Pivot Tables on page 19 for more information.Exampleimportspssspss.StartProcedure("mycompany.com.demoProc")table=spss.BasePivotTable("TableTitle","OMStablesubtype")table.SimplePivotTable(rowdim="rowdimension",rowlabels=["firstrow","secondrow"],coldim="columndimension",collabels=["firstcolumn","secondcolumn"],cells=[11,12,21,22])spss.EndProcedure()Resultv This example shows how to generate a pivot table within a spss.StartProcedure-spss.EndProcedureblock. The argument to the StartProcedure function specifies a name to associate with the output. Thisis the name that appears in the outline pane of the Viewer associated with the output--in this case,mycompany.com.demoProc. It is also the command name associated with this output when routing outputwith OMS.Note: In order that names associated with output do not conflict with names of existing IBM SPSSStatistics commands (when working with OMS), it is recommended that they have the formyourcompanyname.com.procedurename. See the topic spss.StartProcedure Function on page 86 for moreinformation.v You create a pivot table by first creating an instance of the BasePivotTable class and storing it to avariable--in this case, the variable table.v The SimplePivotTable method of the BasePivotTable instance is called to create the structure of thetable and populate its cells. Row and column labels and cell values can be specified as character stringsor numeric values. They can also be specified as a CellText object. CellText objects allow you tospecify that category labels be treated as variable names or variable values, or that cell values bedisplayed in one of the numeric formats used in IBM SPSS Statistics pivot tables, such as the format fora mean. When you specify a category as a variable name or variable value, pivot table display optionssuch as display variable labels or display value labels are honored.v Numeric values specified for cell values, row labels, or column labels, are displayed using the defaultformat for the pivot table. Instances of the BasePivotTable class have an implicit default format ofGeneralStat. You can change the default format using the SetDefaultFormatSpec method.Figure 2. Simple pivot table18 Python Reference Guide for IBM SPSS Statisticsv spss.EndProcedure marks the end of output creation.General Approach to Creating Pivot TablesThe BasePivotTable class provides a variety of methods for creating pivot tables that cannot be createdwith the SimplePivotTable method. The basic steps for creating a pivot table are:1. Create an instance of the BasePivotTable class.2. Add dimensions.3. Define categories.4. Set cell values.Once a cell value has been set, you can access its value. This is convenient for cell values that depend onthe value of another cell. See the topic Using Cell Values in Expressions on page 23 for moreinformation.Related information:Step 1: Adding DimensionsStep 2: Defining Categories on page 20Step 3: Setting Cell Values on page 21Step 1: Adding DimensionsYou add dimensions to a pivot table with the Append or Insert method.Example: Using the Append Methodtable=spss.BasePivotTable("TableTitle","OMStablesubtype")coldim=table.Append(spss.Dimension.Place.column,"coldim")rowdim1=table.Append(spss.Dimension.Place.row,"rowdim-1")rowdim2=table.Append(spss.Dimension.Place.row,"rowdim-2")v The first argument to the Append method specifies the type of dimension, using one member from a setof built-in object properties: spss.Dimension.Place.row for a row dimension,spss.Dimension.Place.column for a column dimension, and spss.Dimension.Place.layer for a layerdimension.v The second argument to Append is a string that specifies the name used to label this dimension in thedisplayed table.v Although not required to append a dimension, it's good practice to store a reference to the newlycreated dimension object in a variable. For instance, the variable rowdim1 holds a reference to the objectfor the row dimension named rowdim-1. Depending on which approach you use for setting categories,you may need this object reference.The order in which the dimensions are appended determines how they are displayed in the table. Eachnewly appended dimension of a particular type (row, column, or layer) becomes the current innermostdimension in the displayed table. In the example above, rowdim-2 is the innermost row dimension since itis the last one to be appended. Had rowdim-2 been appended first, followed by rowdim-1, rowdim-1 wouldbe the innermost dimension.Note: Generation of the resulting table requires more code than is shown here.Figure 3. Resulting table structurePython Functions and Classes 19Example: Using the Insert Methodtable=spss.BasePivotTable("TableTitle","OMStablesubtype")rowdim1=table.Append(spss.Dimension.Place.row,"rowdim-1")rowdim2=table.Append(spss.Dimension.Place.row,"rowdim-2")rowdim3=table.Insert(2,spss.Dimension.Place.row,"rowdim-3")coldim=table.Append(spss.Dimension.Place.column,"coldim")v The first argument to the Insert method specifies the position within the dimensions of that type (row,column, or layer). The first position has index 1 (unlike typical Python indexing that starts with 0) anddefines the innermost dimension of that type in the displayed table. Successive integers specify thenext innermost dimension and so on. In the current example, rowdim-3 is inserted at position 2 androwdim-1 is moved from position 2 to position 3.v The second argument to Insert specifies the type of dimension, using one member from a set ofbuilt-in object properties: spss.Dimension.Place.row for a row dimension,spss.Dimension.Place.column for a column dimension, and spss.Dimension.Place.layer for a layerdimension.v The third argument to Insert is a string that specifies the name used to label this dimension in thedisplayed table.v Although not required to insert a dimension, it is good practice to store a reference to the newlycreated dimension object to a variable. For instance, the variable rowdim3 holds a reference to the objectfor the row dimension named rowdim-3. Depending on which approach you use for setting categories,you may need this object reference.Note: Generation of the resulting table requires more code than is shown here.Step 2: Defining CategoriesThere are two ways to define categories for each dimension: explicitly, using the SetCategories method, orimplicitly when setting values. The explicit method is shown here. The implicit method is shown in Step3: Setting Cell Values on page 21.ExamplefromspssimportCellTexttable=spss.BasePivotTable("TableTitle","OMStablesubtype")coldim=table.Append(spss.Dimension.Place.column,"coldim")rowdim1=table.Append(spss.Dimension.Place.row,"rowdim-1")rowdim2=table.Append(spss.Dimension.Place.row,"rowdim-2")cat1=CellText.String("A1")cat2=CellText.String("B1")cat3=CellText.String("A2")cat4=CellText.String("B2")cat5=CellText.String("C")cat6=CellText.String("D")cat7=CellText.String("E")table.SetCategories(rowdim1,[cat1,cat2])table.SetCategories(rowdim2,[cat3,cat4])table.SetCategories(coldim,[cat5,cat6,cat7])v The statementfromspssimportCellText allows you to omit thespss prefix when specifyingCellText objects (discussed below), once you have imported the spss module.v You set categories after you add dimensions, so the SetCategories method calls follow the Append orInsert method calls.Figure 4. Resulting table structure20 Python Reference Guide for IBM SPSS Statisticsv The first argument to SetCategories is an object reference to the dimension for which the categoriesare being defined. This underscores the need to save references to the dimensions you create withAppend or Insert, as discussed in the previous topic.v The second argument to SetCategories is a single category or a sequence of unique category values,each expressed as a CellText object (one of CellText.Number, CellText.String, CellText.VarName, orCellText.VarValue). When you specify a category as a variable name or variable value, pivot tabledisplay options such as display variable labels or display value labels are honored. In the presentexample, we use string objects whose single argument is the string specifying the category.v It is a good practice to assign variables to the CellText objects representing the category names, sinceeach category will often need to be referenced more than once when setting cell values.Note: Generation of the resulting table requires more code than is shown here.Step 3: Setting Cell ValuesThere are two primary methods for setting cell values: setting values one cell at a time by specifying thecategories that define the cell, or using the SetCellsByRow or SetCellsByColumn method.Example: Specifying Cells by Their Category ValuesThis example reproduces the table created in the SimplePivotTable example.fromspssimportCellTexttable=spss.BasePivotTable("TableTitle","OMStablesubtype")table.Append(spss.Dimension.Place.row,"rowdimension")table.Append(spss.Dimension.Place.column,"columndimension")row_cat1=CellText.String("firstrow")row_cat2=CellText.String("secondrow")col_cat1=CellText.String("firstcolumn")col_cat2=CellText.String("secondcolumn")table[(row_cat1,col_cat1)]=CellText.Number(11)table[(row_cat1,col_cat2)]=CellText.Number(12)table[(row_cat2,col_cat1)]=CellText.Number(21)table[(row_cat2,col_cat2)]=CellText.Number(22)v The Append method is used to add a row dimension and then a column dimension to the structure ofthe table. The table specified in this example has one row dimension and one column dimension.Notice that references to the dimension objects created by the Append method are not saved tovariables, contrary to the recommendations in the topic on adding dimensions. When setting cellsusing the current approach, these object references are not needed.v For convenience, variables consisting of CellText objects are created for each of the categories in thetwo dimensions.v Cells are specified by their category values in each dimension. In the tuple (or list) that specifies thecategory values--for example, (row_cat1,col_cat1)--the first element corresponds to the first appendeddimension (what we have named "row dimension") and the second element to the second appendedFigure 5. Resulting table structurePython Functions and Classes 21dimension (what we have named "column dimension"). The tuple (row_cat1,col_cat1) then specifiesthe cell whose "row dimension" category is "first row" and "column dimension" category is "firstcolumn."v You may notice that the example does not make use of the SetCategories method to define the rowand column dimension category values. When you assign cell values in the manner donehere--table[(category1,category2)]--the values provided to specify the categories for a given cell areused by the BasePivotTable object to build the set of categories for the table. Values provided in thefirst element of the tuple (or list) become the categories in the dimension created by the first methodcall to Append or Insert. Values in the second element become the categories in the dimension createdby the second method call to Append or Insert, and so on. Within a given dimension, the specifiedcategory values must be unique. The order of the categories, as displayed in the table, is the order inwhich they are created from table[(category1,category2)]. In the example shown above, the rowcategories will be displayed in the order "first row," "second row."v Cell values must be specified as CellText objects (one of CellText.Number, CellText.String,CellText.VarName, or CellText.VarValue).v In this example, Number objects are used to specify numeric values for the cells. Values will beformatted using the table's default format. Instances of the BasePivotTable class have an implicitdefault format of GeneralStat. You can change the default format using the SetDefaultFormatSpecmethod, or you can override the default by explicitly specifying the format, as in:CellText.Number(22,spss.FormatSpec.Correlation). See the topic Number Class on page 33 formore information.Example: Setting Cell Values by Row or ColumnThe SetCellsByRow and SetCellsByColumn methods allow you to set cell values for entire rows orcolumns with one method call. To illustrate the approach, we will use the SetCellsByRow method toreproduce the table created in the SimplePivotTable example. It is a simple matter to rewrite the exampleto set cells by column.Note: You can only use the SetCellsByRow method with pivot tables that have one column dimension andyou can only use the SetCellsByColumn method with pivot tables that have one row dimension.fromspssimportCellTexttable=spss.BasePivotTable("TableTitle","OMStablesubtype")rowdim=table.Append(spss.Dimension.Place.row,"rowdimension")coldim=table.Append(spss.Dimension.Place.column,"columndimension")row_cat1=CellText.String("firstrow")row_cat2=CellText.String("secondrow")col_cat1=CellText.String("firstcolumn")col_cat2=CellText.String("secondcolumn")table.SetCategories(rowdim,[row_cat1,row_cat2])table.SetCategories(coldim,[col_cat1,col_cat2])table.SetCellsByRow(row_cat1,[CellText.Number(11),CellText.Number(12)])table.SetCellsByRow(row_cat2,[CellText.Number(21),CellText.Number(22)])v The SetCellsByRow method is called for each of the two categories in the row dimension.v The first argument to the SetCellsByRow method is the row category for which values are to be set. Theargument must be specified as a CellText object (one of CellText.Number, CellText.String,CellText.VarName, or CellText.VarValue). When setting row values for a pivot table with multiple rowdimensions, you specify a list of category values for the first argument to SetCellsByRow, where eachelement in the list is a category value for a different row dimension.v The second argument to the SetCellsByRow method is a list or tuple of CellText objects (one ofCellText.Number, CellText.String, CellText.VarName, or CellText.VarValue) that specify the elements22 Python Reference Guide for IBM SPSS Statisticsof the row, one element for each column category in the single column dimension. The first element inthe list or tuple will populate the first column category (in this case, col_cat1), the second will populatethe second column category, and so on.v In this example, Number objects are used to specify numeric values for the cells. Values will beformatted using the table's default format. Instances of the BasePivotTable class have an implicitdefault format of GeneralStat. You can change the default format using the SetDefaultFormatSpecmethod, or you can override the default by explicitly specifying the format, as in:CellText.Number(22,spss.Forma