2017-09-05 4 views
6

私がデータフレーム持っているまで追加:のpythonは、データフレーム内の行を結合した値

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

をし、私は1つの行に型Tを組み合わせて、2つ(またはそれ以上)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つ以上の列を持つデータフレームがある場合、このコードをどのように変更できますか?と質問してもらいたいのですが、1つの列の値を加算し、残りの列を変更しないでください。つまり、 'Type'と 'Volume'の代わりに、 'Type'、 'Time'、 'Volume'などを取得し、 'Volume'の値を加算したいだけです。 – bing

+0

要素を結合リストに追加すると'df.iloc [i、col]'に置くだけで、 'col'は 'Time 'カラムのカラムインデックスです。 'df.iloc [i、1]])' combined.append([df.iloc [i、0]、df.iloc [i、1]]) (['T'、sum_elements(df、i、i + num_elements、1)]) 'は' combined.append(['T'、df.iloc [i、2]]) 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-and-add-up-value – 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-continuous-data-in-a-data-add-up-value – bing

+0

@bing同じ質問が繰り返されますか? – jdehesa

+0

全く同じではなく、新しいデータフレームには2つ以上のカラムがあります – bing

関連する問題