Reputation: 9363
I have a table with many columns. I am only interested in two columns. Lets call them A and B. I would like to create an empty column, say C = [ ] and append values to it according to some conditions.
A B
1 10
0 11
0 12
1 09
0 14
0 13
1 12
Lets take the above table as an example. If the value in column A==1 then append the value of B for which A==1 to column C (the empty list) until the next A==1 appears in column A. For the next value of 1 in column A, do the above.
So I would want my column C to look like this:
A B C
1 10 10
0 11 10
0 12 10
1 09 09
0 14 09
0 13 09
1 12 12
So as you can see, for the first A==1, C has the value of B for which A==1 until the next A==1 appears.
I was trying something like this, but it is not working:
for i in A:
if i == 1:
C.append(B[A==i])
But this loops through my entire column A and appends many lists.
How can I go about doing it?
Upvotes: 0
Views: 595
Reputation: 117856
A = [1,0,0,1,0,0,1]
B = [10,11,12,9,14,13,12]
C = []
temp = B[0] # Initialize a temporary variable to the first item in B
for i in range(len(B)):
if A[i] == 1:
temp = B[i] # Only update temp if 1 was in the A column
C.append(temp)
>>> C
[10, 10, 10, 9, 9, 9, 12]
Walking through a few iterations of the for
loop:
i = 0
, A[0]
is 1
, temp
becomes B[0]
which is 10
i = 1
, A[1]
is 0
, temp
stays B[0]
which is still 10
i = 2
, A[2]
is 0
, temp
stays B[0]
which is still 10
i = 3
, A[3]
is 1
, temp
becomes B[3]
which is 9
... etc
Upvotes: 2