2016-08-14 10 views
0

私はデータベースにクエリを行い、パンダのデータフレームを設定しています。私は(groupbyを介して)データを集計し、テーブル内の日付がインデックスになるようにデータフレームインデックスを操作することに苦労しています。 ここでは、groupbyの前後のデータの表示例と、最終的に探しているものの例を示します。パンダはデータフレームを操作します

データフレーム - 人口データ

firm | dates | received | Sent 
----------------------------------------- 
A  10/08/2016  2   8 
A  12/08/2016  4   2 
B  10/08/2016  1   0 
B  11/08/2016  3   5 
A  13/08/2016  5   1 
C  14/08/2016  7   3 
B  14/08/2016  2   5 
  1. まず私は "しっかり" と "日付" は、グループにしたいと、 "送信/受信"。

  2. 次に、日付が行インデックスではなくインデックスになるようにDataFrameを操作します。最後に、企業のいくつかは、いくつかの日または受信または送信のいずれかで、少なくとも無活動中の活動」を持たない

  3. 日ごとに合計列を追加するには

  4. 。しかし、過去のX日のビューを元に戻すには、空の値が不可能ではなく、値としてゼロを書き込む必要があります。

dates  | 10/08/2016 | 11/08/2016| 12/08/2016| 13/08/2016| 14/08/2016  
firm | 
---------------------------------------------------------------------- 
A  received  2   0   4   5   0 
     sent   8   0   2   1   0 

B  received  1   3   1   0   2 
     sent   0   5   0   0   5 

C  received  0   0   2   0   1 
     sent   0   0   1   2   0 

Totals r.   3   3   7   5   3    
Totals s.   8   0   3   3   5 

私は、次のコードを試してみた:

df = > mysql query result 

n_received = df.groupby(["firm", "dates" 
           ]).received.size() 

n_sent = df.groupby(["firm", "dates" 
           ]).sent.size() 

tables = pd.DataFrame({ 'received': n_received, 'sent': n_sent, 
          }, 
          columns=['received','sent']) 

this = pd.melt(tables, 
        id_vars=['dates', 
          'firm', 
          'received', 'sent'] 

this = this.set_index(['dates', 
         'firm', 
         'received', 'sent' 
        'var' 
        ])   
this = this.unstack('dates').fillna(0)  

this.columns = this.columns.droplevel() 

this.columns.name = '' 

this = this.transpose() 

基本的に、私はこのコードをもとにしたい結果になっていません。 - どうすればいいですか? - 概念的には、この結果を達成するより良い方法がありますか? SQLステートメントでの集計、またはPandasでの集計は最適化の観点から理にかなっており、論理的には意味があります。

答えて

0

あなたは(ワイドロングに)ワイドに長いからデータを変換するフォーマットをstackunstack)を使用することができます。私はあなたのソリューションで行くを持っています

import pandas as pd 
# calculate the total received and sent grouped by dates 
df1 = df.drop('firm', axis = 1).groupby('dates').sum().reset_index() 

# add total category as the firm column 
df1['firm'] = 'total' 

# concatenate the summary data frame and original data frame use stack and unstack to 
# transform the data frame so that dates appear as columns while received and sent stack as column. 
pd.concat([df, df1]).set_index(['firm', 'dates']).stack().unstack(level = 1).fillna(0) 

# dates   10/08/2016 11/08/2016 12/08/2016 13/08/2016 14/08/2016 
# firm      
#  A  Sent  8.0   0.0   2.0   1.0   0.0 
#  received  2.0   0.0   4.0   5.0   0.0 
#  B  Sent  0.0   5.0   0.0   0.0   5.0 
#  received  1.0   3.0   0.0   0.0   2.0 
#  C  Sent  0.0   0.0   0.0   0.0   3.0 
#  received  0.0   0.0   0.0   0.0   7.0 
# total  Sent  8.0   5.0   2.0   1.0   8.0 
#  received  3.0   3.0   4.0   5.0   9.0 
+0

感謝 – OAK

関連する問題