3
votes

Trying to use SPSS/Python I would like change variable names for certain variables.
For example, I need all variables with the

oldname = t1XXX to change to newname = t01XXX

Tried to play with code I found around here (like below), but could not change this properly to do what I need. Thanks for any hints!


Example from Jignesh Sutar; strip-suffix-from-all-variable-names-in-spss/34816192#34816192)

begin program.
spss.Submit(r"set mprint on.")
import spss, spssaux
allvarlist=[str(v) for v in spssaux.VariableDict()]
filteredvarlist=[v for v in allvarlist if v.endswith("_1")]
spss.Submit( "rename variables (\n" \
     + "\n".join(filteredvarlist) \
     + "\n=\n" \
     + "\n".join([v[:-2] for v in filteredvarlist]) \
     + ").")
spss.Submit(r"set mprint off.")
end program.
1
Is the change you are attempting to do is convert the numeric portion consistently to a two digit number? I.e if it is t10xxx then no change to be made?Jignesh Sutar
Thanks for the follow-up question; I have different variants of this in my data, this was just an example. I think my main problem is that I have no idea how Python regular expressions to select the variables I want interact with SPSS syntax... :-)Esther Fujiwara

1 Answers

2
votes

Here is a program to do this. It first creates a variable dictionary for all names that start with t followed by a single digit followed by a nondigit. Then it generates a RENAME VARIABLES command adding in a leading 0.

Here is the code:

import spss, spssaux  

vardict = spssaux.VariableDict(pattern="t\d\D")  
newnames = [v[0] + "0" + v[1:] for v in vardict.variables]  
cmd = """rename variables (%s=%s)""" % \  
(" ".join(vardict.variables), " ".join(newnames))  
spss.Submit(cmd)