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热门推荐
10 长辈生日横幅祝福语简短
11 运动社团祝福语简短英文
12 新年祝福语简短 经典短句
13 朋友妹妹高考祝福语简短
14 食堂阿姨退休祝福语简短
15 郭可盈老公生日祝福语简短
16 新年送顾客祝福语简短
17 外国媳妇订婚祝福语简短
18 喜庆节的祝福语简短