how do i loop over values within a for loop in python?

I have a df

    1   1   2   2
    2   2   1   1

I have written a function which:
takes the df
in a for loop, adds row(s) with a default value
replaces the values with another value in randomly selected cols
writes to csv

This is my code.

def add_x(df, max):
    gt_w_x = df.copy()
    counter = 0


    for i in range(1, max):
        if len(gt_w_x) != max:
            counter+=1
            # add new row with default value
            gt_w_x.loc[-1,:] = 1
        
            # reset index
            gt_w_x = gt_w_x.reset_index(drop=True)
        
            # how to loop over these values for x ??
            x = 1
            #x = 2
        
            # assign value 'X' to x randomly selected cols on last row 
            gt_w_x.iloc[-1:, random.sample(list(range(gt_w_x.shape[1])), x)] = 'X'
        
            x = str(x)
            n = str(counter)
        
            # write to file
            df_path = 'test/' + x + '_' + n + '.csv'
            gt_w_x.to_csv(df_path) 

max = 4
add_x(df, max)

The output on my system is
test/1_1.csv
test/1_2.csv

cat test/1_1.csv
0,1.0,1.0,2.0,2.0
1,2.0,2.0,1.0,1.0
2,1.0,X,1.0,1.0

cat test/1_2.csv
0,1.0,1.0,2.0,2.0
1,2.0,2.0,1.0,1.0
2,1.0,X,1.0,1.0
3,1.0,X,1.0,1.0

How do I loop over values for x? The desired output for x = 1 and x = 2 is
test/1_1.csv
test/1_2.csv
test/2_1.csv
test/2_2.csv

Currently, I run the function by commenting out different values for x which is suboptimal.



Comments

Popular posts from this blog

Spring Elasticsearch Operations

Network Error and Timeout on Authorize.net JS

Object oriented programming concepts (OOPs)