I have a list of values in a column (A) and want to increment by 1 in column (B) until the value in A changes, however, having difficulty in my loop to reset the increment when A changes.
B = [] list_length = len(A) for i in range(0, list_length): j = 1 while A[i] == A[i+1]: B = j j += 1 i += 1 else: B = 1 j += 1
Here is desired output:
Product(A) | No.(B) |
---|---|
Apple | 1 |
Apple | 2 |
Apple | 3 |
Orange | 1 |
Orange | 2 |
Orange | 3 |
Orange | 4 |
Orange | 5 |
Orange | 6 |
Melon | 1 |
Melon | 2 |
Peach | 1 |
Peach | 2 |
Peach | 3 |
Peach | 4 |
Advertisement
Answer
The other two answers are awesome, but I was initially stuck to follow your initial approach with the counter, so here’s what I did:
from prettytable import PrettyTable fruit_table = PrettyTable(["Product(A)", "No.(B)"]) products = ["Apple", "Apple","Apple", "Orange","Orange","Orange","Orange","Orange","Melon","Melon", "Peach","Peach","Peach"] counter = 0 for i in range(0, len(products)-1): if products[i] == products[i+1]: counter+= 1 fruit_table.add_row([products[i],counter]) else: fruit_table.add_row([products[i],counter+1]) counter=0 print(fruit_table)
Output:
+------------+--------+ | Product(A) | No.(B) | +------------+--------+ | Apple | 1 | | Apple | 2 | | Apple | 3 | | Orange | 1 | | Orange | 2 | | Orange | 3 | | Orange | 4 | | Orange | 5 | | Melon | 1 | | Melon | 2 | | Peach | 1 | | Peach | 2 | +------------+--------+