Hasnep
Hasnep

Reputation: 121

Using Python to overwrite SPSS variable

My SPSS dataset contains two variables with names time1 and time2 and labels time1 and time2 respectively. Eventually, I want to use Python to read the variables and modify them. As a simple test, I am trying to replace every entry of time1 with "hello". This is the SPSS syntax I am using:

begin program python.
import spss, spssdata

data = spssdata.Spssdata(indexes=["time1"], accessType="w")

for row in data:
    data.setvalue("time1", "hello")
    data.CommitCase()

data.CClose()
end program.

But I am getting the following error:

Warning: An open Cursor was detected while exiting a program block. The Cursor has been closed. Traceback (most recent call last):
File "", line 5, in File "C:\PROGRA~1\PREDIC~1\PSIMAG~1\5\IBM\SPSS\STATIS~1\25\PYTHON\Lib\site- packages\spssdata\spssdata.py", line 467, in setvalue index = [varspec[0] for varspec in self.newvars].index(var) ValueError: 'time1' is not in list

What am I missing here? Thank you.

My variables:

My variables

Upvotes: 0

Views: 917

Answers (1)

Hasnep
Hasnep

Reputation: 121

It is not possible to overwrite data using Python using the spssdata module becuase it uses the Cursor object from the spss module, which cannot overwrite variables. It is possible to create a new variable and set its values using Python. You can then also delete the old variable and rename the new variable to the same name as the old one.

From Programming and Data Management for IBM SPSS Statistics 23: A Guide for IBM SPSS Statistics and SAS Users, page 167:

write mode allows you to add new variables (and their case values) to the active dataset

Upvotes: 0

Related Questions