私はこれが役立つと思います。このコードは、連続する任意の数の 'T'を扱うことができ、結合する文字を変更することさえできます。私はそれが何をしているのかを説明するコードにコメントを追加しました。
https://pastebin.com/FakbnaCj
import pandas as pd
def combine(df):
combined = [] # Init empty list
length = len(df.iloc[:,0]) # Get the number of rows in DataFrame
i = 0
while i < length:
num_elements = num_elements_equal(df, i, 0, 'T') # Get the number of consecutive 'T's
if num_elements <= 1: # If there are 1 or less T's, append only that element to combined, with the same type
combined.append([df.iloc[i,0],df.iloc[i,1]])
else: # Otherwise, append the sum of all the elements to combined, with 'T' type
combined.append(['T', sum_elements(df, i, i+num_elements, 1)])
i += max(num_elements, 1) # Increment i by the number of elements combined, with a min increment of 1
return pd.DataFrame(combined, columns=df.columns) # Return as DataFrame
def num_elements_equal(df, start, column, value): # Counts the number of consecutive elements
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): # Sums the elements from start to end
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))
それはあなたの質問https://stackoverflow.com/a/45679091/4365003 – RagingRoosevelt
に対処するために開始する可能性がありますようにこれが見えます私は種類の異なるだと思う...私の代わりに、行を結合したいですそれらを数えます – bing
~~別の集計関数を使用していませんか?~~ – RagingRoosevelt