-2

I have a list of file

file_names=['file1.sav', 'file2.sav']

and a list of variables names

var_names=['var1', 'var2']

I want to assign every item in var_names a read_spss function.

so that ill get

var1= pd.read_spss('file1.sav')
var2= pd.read_spss('file2.sav')

Thanks

DOOM
  • 1,170
  • 6
  • 20
yona
  • 15
  • 5
  • 2
    In my opinion consider using a dictionary instead of individual variable names. – Scott Boston Mar 26 '20 at 18:52
  • Can you clarify what exactly the issue is? – AMC Mar 26 '20 at 19:14
  • Does this answer your question? [How do I create a variable number of variables?](https://stackoverflow.com/questions/1373164/how-do-i-create-a-variable-number-of-variables) – AMC Mar 26 '20 at 19:16

1 Answers1

2

Like the comment above the easiest way to do this is with a dictionary.

#create empty dictionary
files = {}

file_names=['file1.sav', 'file2.sav']
var_names=['var1', 'var2']

#loop over both file_names and var_names and use them to build the dictionary
for var_name, file in zip(var_names, file_names):
    files[var_name] = pd.read_spss(file)

That way then you can just access it like this files['var1'] to get the content of file1.sav1.

Matthew Barlowe
  • 2,229
  • 1
  • 14
  • 24