I think this will help. This code can handle any number of consecutive Ts, and you can even change which character to combine. I added comments to the code to explain what it does.
https://pastebin.com/FakbnaCj
import pandas as pd
def combine(df):
combined = []
length = len(df.iloc[:,0])
i = 0
while i < length:
num_elements = num_elements_equal(df, i, 0, 'T')
if num_elements <= 1:
combined.append([df.iloc[i,0],df.iloc[i,1]])
else:
combined.append(['T', sum_elements(df, i, i+num_elements, 1)])
i += max(num_elements, 1)
return pd.DataFrame(combined, columns=df.columns)
def num_elements_equal(df, start, column, value):
i = start
num = 0
while i < len(df.iloc[:,column]):
if df.iloc[i,column] == value:
num += 1
i += 1
else:
return num
return num
def sum_elements(df, start, end, column):
return sum(df.iloc[start:end, column])
frame = pd.DataFrame({"Type": ["Q", "Q", "T", "Q", "T", "T", "Q"],
"Volume": [10, 20, 10, 10, 20, 20, 10]})
print(combine(frame))
source
share