简体   繁体   English

如何使用 Pandas 将数据透视表用于我的 excel 数据

[英]How to use pivot table for my excel data using Pandas

Please find my source data below.请在下面找到我的源数据。

Device   AppVersion Rating
Rolex       5.8.0   3
i5i_2018    5.7.0   2
Galaxy A71  5.6.0   3
vivo1807    5.8.0   1
Redmi Note5 5.7.0   2
realme3     5.7.0   3
Redmi7      5.8.0   1
vivo1816    5.7.1   3
Redmi 8     5.6.0   2
o7prolte    5.8.0   3

I want the total count of ratings for each version as output like below.我想要每个版本的评分总数作为输出,如下所示。

Count of Rating    Column Labels            
RowLabels          5.6.0    5.7.0   5.7.1   5.8.0
1                                           2
2                  1        2       
3                  1        1       1       2

I got this using a Pivot table in excel but was not able to do the same using Pandas.我使用 excel 中的数据透视表得到了这个,但无法使用 Pandas 做同样的事情。 Could anyone provide your insights?有人可以提供您的见解吗?

Try .groupby , and then .unstack the result尝试.groupby ,然后.unstack结果
https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.groupby.html https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.groupby.html
https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.unstack.html https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.unstack.html

df = ...your dataframe...
counts = df.groupby(['Rating','AppVersion']).count()
result = counts.unstack('AppVersion')

This will put blanks in as NaNs pd.np.nan .这会将空白放入 NaN pd.np.nan If you really want to see blank space, fill with an empty string:如果你真的想看到空格,用一个空字符串填充:

result_with_blanks = result.fillna('') 

This will change the data type to object though, so I don't recommend this.不过,这会将数据类型更改为 object,因此我不建议这样做。

You can achieve the pivot table in Pandas using the pivot table method :您可以使用数据透视表方法在 Pandas 中实现数据透视表

 df.pivot_table(index='Rating', 
                columns='AppVersion',
                aggfunc='count',
                fill_value=0)


                                   Device
AppVersion  5.6.0   5.7.0   5.7.1   5.8.0
Rating              
1            0       0       0       2
2            1       2       0       0
3            1       1       1       2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM