Guest User

SO Answer

a guest
Sep 5th, 2017
228
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.36 KB | None | 0 0
  1. import pandas as pd
  2.  
  3. def combine(df):
  4.     combined = [] # Init empty list
  5.     length = len(df.iloc[:,0]) # Get the number of rows in DataFrame
  6.     i = 0
  7.     while i < length:
  8.         num_elements = num_elements_equal(df, i, 0, 'T') # Get the number of consecutive 'T's
  9.         if num_elements <= 1: # If there are 1 or less T's, append only that element to combined, with the same type
  10.             combined.append([df.iloc[i,0],df.iloc[i,1]])
  11.         else: # Otherwise, append the sum of all the elements to combined, with 'T' type
  12.             combined.append(['T', sum_elements(df, i, i+num_elements, 1)])
  13.         i += max(num_elements, 1) # Increment i by the number of elements combined, with a min increment of 1
  14.     return pd.DataFrame(combined, columns=df.columns) # Return as DataFrame
  15.  
  16. def num_elements_equal(df, start, column, value): # Counts the number of consecutive elements
  17.     i = start
  18.     num = 0
  19.     while i < len(df.iloc[:,column]):
  20.         if df.iloc[i,column] == value:
  21.             num += 1
  22.             i += 1
  23.         else:
  24.             return num
  25.     return num
  26.  
  27. def sum_elements(df, start, end, column): # Sums the elements from start to end
  28.     return sum(df.iloc[start:end, column])
  29.  
  30. frame = pd.DataFrame({"Type":   ["Q", "Q", "T", "Q", "T", "T", "Q"],
  31.                    "Volume": [10,   20,  10,  10,  20,  20,  10]})
  32. print(combine(frame))
Add Comment
Please, Sign In to add comment