Mason J.
Mason J.

Reputation: 65

Iterating column data in row iteration

I am making a loop of random numbers, but also want to loop in an already available column of data from another file.

Simplified example:

out = /location/of/test.txt
file = open(out,'w')

var = [7,12,1,35,4]

for num in range(5):
    a = randint(1,10)
    file.write('%i ' % a)

    b = randint(1,10)
    file.write('%i ' % b)

file.write('\n')

The result I want is:

4   10  7
10  8   12
7   2   1
6   5   35
9   8   4

My problem is, how to I loop in my var array into my code?

I tried something like:

for num in range(5):
    a = randint(1,10)
    file.write('%i ' % a)

    b = randint(1,10)
    file.write('%i ' % b)

    for c in var:
       file.write('%i ' % c)

file.write('\n') 

But the result would be:

4   10  7 12 1 35 4
10  8   7 12 1 35 4
7   2   7 12 1 35 4
6   5   7 12 1 35 4
9   8   7 12 1 35 4

I understand why that is the result, I just don't know how to iterate through my var as well as the generated numbers loop to create the format I want.

Upvotes: 0

Views: 55

Answers (3)

Mason J.
Mason J.

Reputation: 65

out = /location/of/test.txt
file = open(out,'w')

df = some dataframe
df[:,4] = [7,12,1,35,4]

for col in range(len(df.index)):
    a = randint(1,10)
    file.write('%i ' % a)

    b = randint(1,10)
    file.write('%i ' % b)

    c = (df.iloc[[col],4])
    file.write('%.i ' % c)

    file.write('\n') 

Upvotes: 0

IamBatman
IamBatman

Reputation: 1015

Unless I'm misunderstanding you, this should be the way it should be written. You have 5 variables in the var array. Loop through the array and do the rest of the logic below it.

out = /location/of/test.txt
file = open(out,'w')

var = [7,12,1,35,4]

for c in var:
    a = randint(1,10)
    file.write('%i ' % a)

    b = randint(1,10)
    file.write('%i ' % b)

    file.write('%i ' % c)

    file.write('\n') 

Upvotes: 0

jpp
jpp

Reputation: 164673

You don't use num anywhere, so just iterate over var directly. I also recommend you use a with clause with open and utilize f-strings, which are available in Python 3.6+:

out = 'test.txt'
var = [12,12,12,12,12]
a, b = 10, 11

with open(out, 'w') as fin:
    for val in var:
        fin.write(f'{a} {b} {val}\n')

Output:

10 11 12
10 11 12
10 11 12
10 11 12
10 11 12

Upvotes: 1

Related Questions