2列のPandasデータフレームがあるとします。df.Price
およびdf.Revenue
。df.Price.value_counts(bins=[5,10,15])
3つのビンのそれぞれの価格の数を実行して決定できます。
ただし、Price
列に指定したこれらのビン内の総収益を知りたいのですが。どうすればこれを達成できますか?それに対する拡張は、これらのビンのそれぞれのトランザクションの数(カウント)を見つけることでしょうか?
pd.cut
バケットを含むダミー列を作成し、その上でグループ化するために使用します。
>>> df = pd.DataFrame({'Price': np.random.randint(0,20,(10,)),
'Revenue': np.random.rand(10)})
>>> df
Price Revenue
0 0 0.104462
1 9 0.976338
2 7 0.800895
3 13 0.700494
4 13 0.241352
5 0 0.535348
6 13 0.811419
7 17 0.508165
8 13 0.580809
9 5 0.711055
>>> df['Bucket'] = pd.cut(df['Price'], [-float('inf'), 5, 10, 15, float('inf')])
>>> df
Price Revenue Bucket
0 0 0.104462 (-inf, 5.0]
1 9 0.976338 (5.0, 10.0]
2 7 0.800895 (5.0, 10.0]
3 13 0.700494 (10.0, 15.0]
4 13 0.241352 (10.0, 15.0]
5 0 0.535348 (-inf, 5.0]
6 13 0.811419 (10.0, 15.0]
7 17 0.508165 (15.0, inf]
8 13 0.580809 (10.0, 15.0]
9 5 0.711055 (-inf, 5.0]
>>> df.groupby('Bucket').sum()
Price Revenue
Bucket
(-inf, 5.0] 5 1.350865
(5.0, 10.0] 16 1.777233
(10.0, 15.0] 52 2.334075
(15.0, inf] 17 0.508165
>>> df.groupby('Bucket')['Revenue']
.agg(['count', 'sum'])
.rename(columns={'sum': 'Net Revenue'})
count Net Revenue
Bucket
(-inf, 5.0] 3 2.266008
(5.0, 10.0] 3 1.477182
(10.0, 15.0] 1 0.432358
(15.0, inf] 3 2.097361
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加