2017-09-05 50 views
6

我有一个数据帧:蟒蛇在数据帧相结合的行和加起来值

Type: Volume: 
Q  10 
Q  20 
T  10 
Q  10 
T  20 
T  20 
Q  10 

,我想T型结合起来,一个行并添加了体积只有两个(或更多)TS是连续

即:

Q 10 
Q 20 
T 10 
Q 10 
T 20+20=40 
Q 10 

有没有什么办法来实现这一目标? DataFrame.groupby会工作吗?

+0

这看起来像它可能开始解决您的问题https://stackoverflow.com/a/45679091/4365003 – RagingRoosevelt

+0

我认为这是一种不同的...我想行,而不是合并的计数他们 – bing

+0

~~你不会只是使用不同的聚合函数,然后?~~ – RagingRoosevelt

回答

1

我认为这将有助于。此代码可以处理任意数量的连续“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)) 
+0

非常感谢您的回复。请问如果我得到的数据框超过2列,我怎么才能更改这段代码?我只想将一列的值加起来,并保持其余的不变?即'Type'和'Volume',我得到'Type','Time','Volume'等,而我只想将'Volume'的值相加 – bing

+0

将元素追加到组合列表('a')放在'df.iloc [i,col]'中,其中col是'时间'列的列索引。 'combined.append([df.iloc [i,0],df.iloc [i,1]])'成为'combined.append([df.iloc [i,0],df.iloc [i,1] ,df.iloc [i,2]])'和'combined.append(['T',sum_elements(df,i,i + num_elements,1)])'''combined.append(['T', df.iloc [i,1],sum_elements(df,i,i + num_elements,2)])' – coolioasjulio

+0

https://stackoverflow.com/questions/46099924/how-to-combine-consecutive-data-in-a -dataframe-和添加了价值 – bing

1

如果你只需要部分资金,这里是一个小把戏做到这一点:

import numpy as np 
import pandas as pd 

df = pd.DataFrame({"Type": ["Q", "Q", "T", "Q", "T", "T", "Q"], 
        "Volume": [10, 20, 10, 10, 20, 20, 10]}) 
s = np.diff(np.r_[0, df.Type == "T"]) 
s[s < 0] = 0 
res = df.groupby(("Type", np.cumsum(s) - 1)).sum().loc["T"] 
print(res) 

输出:

Volume 
0  10 
1  40 
+0

https://stackoverflow.com/questions/ 46099924/how-to-combine-consecutive-data-in-a-dataframe-and-add-up-value – bing

+0

@bing这个问题是否重复? – jdehesa

+0

不完全相同,新的数据框有两列以上的列 – bing