我有一個看起來像這樣的熊貓資料框:
| 型別 | 地位 |
|---|---|
| A型 | 新的 |
| A型 | 在職的 |
| A型 | 在職的 |
| A型 | 關閉 |
| A型 | 關閉 |
| A型 | 關閉 |
| B型 | 新的 |
| B型 | 在職的 |
| C型 | 關閉 |
| C型 | 關閉 |
| C型 | 關閉 |
我想按“型別”欄位對資料框進行分組,并將每個狀態的計數作為一列,如下所示:
| 型別 | 新的 | 在職的 | 關閉 |
|---|---|---|---|
| A型 | 1 | 2 | 3 |
| B型 | 1 | 1 | 0 |
| C型 | 0 | 0 | 3 |
我還想要可能存在的狀態列(我列出了所有可能性),但可能不會在輸入資料框中表示,因此最終結果將是這樣的:
| 型別 | 新的 | 在職的 | 關閉 | 升級 |
|---|---|---|---|---|
| A型 | 1 | 2 | 3 | 0 |
| B型 | 1 | 1 | 0 | 0 |
| C型 | 0 | 0 | 3 | 0 |
我可以使用以下方法獲取每個狀態的計數:
closureCodeCounts = closureCodes.groupby(['type','status'],as_index=False).size()
我也試過
closureCodeCounts = closureCodeCounts.groupby('type').value_counts()
closureCodeCounts = closureCodeCounts.unstack()
但似乎沒有什么是正確的。
我很迷茫。最好的方法是什么?
uj5u.com熱心網友回復:
嘗試如下:
- 用于
pd.crosstab達到所需輸出的第一階段。 - 對于第二階段,我假設
list您提到的確實包含所有可能的值。如果是這樣,我們可以申請df.reindex將axis=1缺失的可能性添加為columns。 - 由于額外的列將添加
NaN值,我們可以使用它df.fillna來獲取零。
possible_statuses = ['New','Working','Closed','Escalate']
res = (pd.crosstab(closureCodes.Type, closureCodes.Status)
.reindex(possible_statuses, axis=1)
.fillna(0))
print(res)
Status New Working Closed Escalate
Type
typeA 1 2 3 0.0
typeB 1 1 0 0.0
typeC 0 0 3 0.0
“化妝品”補充:
res.columns.name = None # to get rid of "Status" as `columns.name`
res = res.astype(int) # to turn `0.0` (floats) for added cols into `0` (integers)
達到第一階段的另一種方法如下:
df.groupby與value_counts和鏈一起使用df.unstack:
res = (closureCodes.groupby('Type')
.value_counts()
.unstack()
.reindex(possible_statuses, axis=1)
.fillna(0))
print(res)
Status New Working Closed Escalate
Type
typeA 1.0 2.0 3.0 0.0
typeB 1.0 1.0 0.0 0.0
typeC 0.0 0.0 3.0 0.0
當然,這與您最初嘗試做的非常接近(但您不需要 middle closureCodeCounts)。
uj5u.com熱心網友回復:
您可以使用資料透視表來轉置分組的資料框 -
closureCodeCounts = pd.pivot_table(closureCodeCounts, values = 'size', index=['type'], columns = 'status').fillna(0)
然后類似于@ouroboros1 的答案,重新索引您的資料框以添加缺失的列。
possible_statuses = ['New','Working','Closed','Escalate']
result = closureCodeCounts.reindex(columns=possible_statuses, fill_value=0)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/524014.html
標籤:Python熊猫
