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を集計するプロセスは、この場合はカテゴリがインデックスの一部になるため、非常にマニュアルになります。
私は絶対的なパンダの脅威です。だから私はこれを実際よりももっと難しくしています。誰もパンダでこのグループを達成するためのヒントを教えてもらえますか?
期待される出力は何ですか? – Vaishali
私はこのソリューションが私のものより優れています。 –