我正在使用帶有如下資料框的熊貓:
| 名稱 | 百分 | 數量 |
|---|---|---|
| 一個 | 3 | 34 |
| 乙 | 5 | 200 |
| C | 30 | 20 |
| D | 1 | 12 |
我想為percent列創建存盤桶,例如0-5, 6-15, >16。使用這些桶,我既記錄了percent列的計數(實際上是一個直方圖),也記錄了同一個桶中的平均值。Amount
使用上面的例子:
| 桶 | 百分比計數 | 平均 數量 |
|---|---|---|
| 5 | 3 | 82 |
| 15 | 0 | 0 |
| >15 | 1 | 20 |
我怎樣才能在python和pandas(或任何其他庫)中實作這一點
uj5u.com熱心網友回復:
您需要使用pandas.cut和groupby agg:
(df.assign(Bucket=pd.cut(df['percent '],
[0, 5, 15, float('inf')],
labels=['0-5', '6-15', '>15']))
.groupby('Bucket').agg(**{'percent count': ('percent ', 'count'),
'Avg. Amount': ('Amount', 'mean')
})
.fillna(0, downcast='infer')
.reset_index()
)
輸出:
Bucket percent count Avg. Amount
0 0-5 3 82
1 6-15 0 0
2 >15 1 20
uj5u.com熱心網友回復:
使用numpy.select,Series.between和Groupby.agg:
In [232]: import numpy as np
In [233]: conds = [df['percent'].between(0,5), df['percent'].between(6,15), df['percent'].gt(15)]
In [234]: choices = ['5', '15', '>15']
In [237]: df['Bucket'] = np.select(conds, choices)
In [245]: res = df.groupby('Bucket').agg({'percent': 'count', 'Amount': 'mean'}).reindex(choices).fillna(0).astype(int).reset_index()
In [246]: res
Out[246]:
Bucket percent Amount
0 5 3 82
1 15 0 0
2 >15 1 20
時間:
@mozway 的解決方案:
In [257]: def f2():
...: (df.assign(Bucket=pd.cut(df['percent'],[0, 5, 15, float('inf')],labels=['0-5', '6-15', '>15'])).groupby('Bucket').agg(**{'percent count': ('percent', 'count'),'Avg. Amount': ('Amount', 'mean')}).fillna(0, dow
...: ncast='infer').reset_index())
...:
In [258]: %timeit f2()
8.02 ms ± 587 μs per loop (mean ± std. dev. of 7 runs, 100 loops each)
我的解決方案:
In [253]: def f1():
...: conds = [df['percent'].between(0,5), df['percent'].between(6,15), df['percent'].gt(15)]
...: choices = ['5', '15', '>15']
...: df['Bucket'] = np.select(conds, choices)
...: res = df.groupby('Bucket').agg({'percent': 'count', 'Amount': 'mean'}).reindex(choices).fillna(0).astype(int).reset_index()
...:
In [254]: %timeit f1()
3.64 ms ± 371 μs per loop (mean ± std. dev. of 7 runs, 100 loops each)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/422930.html
標籤:
下一篇:使用匹配的字串對從資料框中過濾行[str.contains()ANDOperation-Python,Pandas]
