[英]python pivot table of counts
I have a dataframe df as follows: 我有一个数据帧df如下:
| id | movie | value |
|----|-------|-------|
| 1 | a | 0 |
| 2 | a | 0 |
| 3 | a | 20 |
| 4 | a | 0 |
| 5 | a | 10 |
| 6 | a | 0 |
| 7 | a | 20 |
| 8 | b | 0 |
| 9 | b | 0 |
| 10 | b | 30 |
| 11 | b | 30 |
| 12 | b | 30 |
| 13 | b | 10 |
| 14 | c | 40 |
| 15 | c | 40 |
I want to create a 2X2 pivot table of counts as follows: 我想创建一个2X2数据透视表,如下所示:
| Value | count(a) | count(b) | count ( C ) |
|-------|----------|----------|-------------|
| 0 | 4 | 2 | 0 |
| 10 | 1 | 1 | 0 |
| 20 | 2 | 0 | 0 |
| 30 | 0 | 3 | 0 |
| 40 | 0 | 0 | 2 |
I can do this very easily in Excel using Row and Column Labels. 我可以使用行和列标签在Excel中轻松完成此操作。 How can I do this using Python?
我怎么能用Python做到这一点?
By using pd.crosstab
通过使用
pd.crosstab
pd.crosstab(df['value'],df['movie'])
Out[24]:
movie a b c
value
0 4 2 0
10 1 1 0
20 2 0 0
30 0 3 0
40 0 0 2
It can be done this way with Pandas' basic pivot_table
functionality and aggregate functions (also need to import NumPy
). 它可以通过Pandas的基本
pivot_table
功能和聚合函数(也需要import NumPy
)以这种方式完成。 See the answer in this question and Pandas pivot_table
documentation with examples: 请参阅此问题中的答案和Pandas
pivot_table
文档以及示例:
import numpy as np
df = ...
ndf = df.pivot_table(index=['value'],
columns='movie',
aggfunc=np.count_nonzero).reset_index().fillna(0).astype(int)
print(ndf)
value id
movie a b c
0 0 4 2 0
1 10 1 1 0
2 20 2 0 0
3 30 0 3 0
4 40 0 0 2
Since you are familiar with pivot tables in Excel, I'll give you the Pandas pivot_table
method also: 由于您熟悉Excel中的数据透视表,我还将为您提供Pandas
pivot_table
方法:
df.pivot_table('id','value','movie',aggfunc='count').fillna(0).astype(int)
Output: 输出:
movie a b c
value
0 4 2 0
10 1 1 0
20 2 0 0
30 0 3 0
40 0 0 2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.