2017-05-18 1 views
0

私は私のデータの例は次のようになりますB、A値を取ることができ、列を時系列データを持っている、またはC.Pandasで月別にカテゴリの列をカウントするにはどうすればよいですか?

:月ごと

date,category 
2017-01-01,A 
2017-01-15,B 
2017-01-20,A 
2017-02-02,C 
2017-02-03,A 
2017-02-05,C 
2017-02-08,C 

私はグループにしたい私のデータをA列のカウントとB列の列の合計を列a_or_b_countに、Cの数をc_countにそれぞれ格納します。

次の関数を使用してデータを私はいくつかのことを試してみたが、私が行うことができました最も近い前処理にある:

def preprocess(df): 
    # Remove everything more granular than day by splitting the stringified version of the date. 
    df['date'] = pd.to_datetime(df['date'].apply(lambda t: t.replace('\ufeff', '')), format="%Y-%m-%d") 
    # Set the time column as the index and drop redundant time column now that time is indexed. Do this op in-place. 
    df = df.set_index(df.date) 
    df.drop('date', inplace=True, axis=1) 
    # Group all events by (year, month) and count category by values. 
    counted_events = df.groupby([(df.index.year), (df.index.month)], as_index=True).category.value_counts() 
    counted_events.index.names = ["year", "month", "category"] 
    return counted_events 

次私を与える:

year month category 
2017 1  A   2 
      B   1 
     2  C   3 
      A   1 

すべてのAとBを集計するプロセスは、この場合はカテゴリがインデックスの一部になるため、非常にマニュアルになります。

私は絶対的なパンダの脅威です。だから私はこれを実際よりももっと難しくしています。誰もパンダでこのグループを達成するためのヒントを教えてもらえますか?

答えて

3

私はAとBの値を先に組み合わせたので、私は@ Scottボストンのソリューションがより好きですが、投稿しました。

df.date = pd.to_datetime(df.date, format = '%Y-%m-%d') 
df.loc[(df.category == 'A')|(df.category == 'B'), 'category'] = 'AB' 

new_df = df.groupby([df.date.dt.year,df.date.dt.month]).category.value_counts().unstack().fillna(0) 
new_df.columns = ['a_or_b_count', 'c_count'] 
new_df.index.names = ['Year', 'Month'] 

       a_or_b_count c_count 
Year Month  
2017 1  3.0    0.0 
     2  1.0    3.0 
+0

期待される出力は何ですか? – Vaishali

+1

私はこのソリューションが私のものより優れています。 –

関連する問題