计算DataFrame中的出现次数

时间:2016-08-31 13:05:45

标签: python pandas pivot-table reshape crosstab

我采用以下格式的Dataframe:

| Department | Person | Power  | ... |
|------------|--------|--------|-----|
| ABC        | 1234   |  75    | ... |
| ABC        | 1235   |  25    | ... |
| DEF        | 1236   |  50    | ... |
| DEF        | 1237   | 100    | ... |
| DEF        | 1238   |  25    | ... |
| DEF        | 1239   |  50    | ... |

我现在想要得到的是电源列中每个值的出现总和。如何从我的DataFrame中获取此信息?

| Department | 100 |  75 |  50 |  25 |
|------------|-----|-----|-----|-----|
| ABC        |   0 |   1 |   0 |   1 |
| DEF        |   1 |   0 |   2 |   1 |

2 个答案:

答案 0 :(得分:4)

您可以将value_countssort_index一起使用,然后按to_frame生成DataFrame,最后按T进行转置:

print (df.Power.value_counts().sort_index(ascending=False).to_frame().T)
       100  75   50   25 
Power    1    1    2    2

通过评论编辑:

您需要crosstab

print (pd.crosstab(df.Department, df.Power).sort_index(axis=1, ascending=False))
Power       100  75   50   25 
Department                    
ABC           0    1    0    1
DEF           1    0    2    1

使用groupbyunstack加快了另一个解决方案:

print (df.groupby(['Department','Power'])
         .size()
         .unstack(fill_value=0)
         .sort_index(axis=1, ascending=False))

Power       100  75   50   25 
Department                    
ABC           0    1    0    1
DEF           1    0    2    1

如果列groupbyDepartment需要Person,请将Person列添加到groupby第二个位置(谢谢piRSquared):

print (df.groupby(['Department','Person', 'Power'])
         .size()
         .unstack(fill_value=0)
         .sort_index(axis=1, ascending=False))

Power              100  75   50   25 
Department Person                    
ABC        1234      0    1    0    0
           1235      0    0    0    1
DEF        1236      0    0    1    0
           1237      1    0    0    0
           1238      0    0    0    1
           1239      0    0    1    0

EDIT1评论:

如果需要添加其他缺失值,请使用reindex

print (df.groupby(['Department','Power'])
         .size()
         .unstack(fill_value=0)
         .reindex(columns=[100,75,50,25,0], fill_value=0))

Power       100  75   50   25   0  
Department                         
ABC           0    1    0    1    0
DEF           1    0    2    1    0

答案 1 :(得分:1)

或者可以这样做:

>>> df.groupby(['Department','Power']).count().unstack().fillna(0)

           Person               
Power         25   50   75   100
Department                      
ABC           1.0  0.0  1.0  0.0
DEF           1.0  2.0  0.0  1.0