Python Pandas - 计算每组中的行数
使用来计算每组中的行数。导入所需的库-group.size()
import pandas as pd
创建一个数据帧-
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"])
现在,计算组大小以获取每组中的行数。
示例
以下是完整的代码-
import pandas as pd #创建数据框 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'] }) #数据框 print"Dataframe...\n",dataFrame #分组列 new_group = dataFrame.groupby(["Product Category", "Quantity"]) #团体规模 new_group = new_group.size() #数据框 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