Python Pandas - 统计每组中的行数


使用 group.size() 统计每组中的行数。导入必需的库 −

import pandas as pd

创建一个 DataFrame −

dataFrame = pd.DataFrame({'Product Category': ['Computer', 'Mobile Phone', 'Electronics', 'Electronics', 'Computer', 'Mobile Phone'],'Quantity': [10, 50, 10, 20, 25, 50],'Product Name': ['Keyboard', 'Charger', 'SmartTV', 'Camera', 'Graphic Card', 'Earphone'] })

按列分组 −

dataFrame.groupby(["Product Category", "Quantity"])

现在,统计组大小来获取每组中的行数。

示例

以下是完整代码 −

Open Compiler
import pandas as pd # create a dataframe dataFrame = pd.DataFrame({'Product Category': ['Computer', 'Mobile Phone', 'Electronics', 'Electronics', 'Computer', 'Mobile Phone'],'Quantity': [10, 50, 10, 20, 25, 50],'Product Name': ['Keyboard', 'Charger', 'SmartTV', 'Camera', 'Graphic Card', 'Earphone'] }) # dataframe print"Dataframe...\n",dataFrame # grouping columns new_group = dataFrame.groupby(["Product Category", "Quantity"]) # group size new_group = new_group.size() # dataframe print"\nUpdated Dataframe...\n",new_group

输出

将生成以下输出 −

Dataframe...
   Product Category   Product Name   Quantity
0          Computer       Keyboard         10
1      Mobile Phone        Charger         50
2       Electronics        SmartTV         10
3       Electronics         Camera         20
4          Computer   Graphic Card         25
5      Mobile Phone       Earphone         50

Updated Dataframe...
Product Category   Quantity
Computer           10        1
                   25        1
Electronics        10        1
                   20        1
Mobile Phone       50        2
dtype: int64

更新于:2021-09-20

237 次浏览

你的职业生涯从这里开始

完成课程即可获得认证

开始学习
广告