Assigning a variable to an incremented label name

Question:

I’m a little out of touch with programming at the moment and would like to ask for advice on this matter. My question is whether it is possible to assign a changing variable (e.g. 2,3,4) to an incremented variable name (e.g. file1, file2…etc) in a loop?

If so, how can I go about doing that?

I have a segment of a script below that I have been trying to implement the aforementioned function:

var=0
IDnumber=1
for i in range (5):
    Sample_mean=df.iloc[[var,var+1]].mean(axis=0) #calculating mean from two rows in pandas dataframe. Sample_mean is the numerical variable.
    print ("mean of the samples at timepoint 1=")
    print (Sample_mean)
    var_for_row=var_for_row+2
    Sample_mean=df.iloc[[var_for_row,var_for_row+1]].mean(axis=0) 
    print ("mean of the samples at timepoint 2=")
    print (Sample_mean)
    label='file_%d'%(IDnumber,) #I am incrementing the variable label here
    label=str(label)
    global label #This is to avoid the NameError: global name 'pt_1' is not defined error. However, I still get the error.
    label=Sample_mean
    var_for_row+=2
    print 'var_for_row=%s'%var_for_row
    IDnumber+=1
    print file_1 #Error occurs at this line

I tried the code above but I get the error NameError: global name 'file_1' is not defined.

Asked By: Craver2000

||

Answers:

You cannot increment a "name" of a variables. Use list to store multiple values.

You can increment the "text" that a variable holds if you know the pattern.

pat = 'file_{}'
myFiles = []
for n in range(4):
    myFiles.append(pat.format(n))
    print ( myFiles[-1])

print(myFiles)

Output:

file_0
file_1
file_2
file_3
['file_0', 'file_1', 'file_2', 'file_3']

This here:

label='file_%d'%(5,) #I am incrementing the variable label here
# label=str(label) # not needed at all - it is already a string

is the same as

label = 'file_{}'.format(5) # or f'file_{5}' for python3.something

See:

for advanced formatting options.

Answered By: Patrick Artner
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.