Reputation: 41
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.
Upvotes: 3
Views: 1373
Reputation: 5417
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)
Upvotes: 2