Python Pandas – 计数观察
要对观察进行计数,首先使用groupby(),然后使用count()结果。首先,导入所需的库 -
dataFrame = pd.DataFrame({'Product Name': ['Keyboard', 'Charger', 'SmartTV', 'Camera', 'Graphic Card', 'Earphone'],'Product Category': ['Computer', 'Mobile Phone', 'Electronics','Electronics', 'Computer', 'Mobile Phone'],'Quantity': [10, 50, 10, 20, 25, 50]})
将具有重复值的列分组 -
group = dataFrame.groupby("Product Category")
获取计数 -
group.count()
示例
以下是代码 -
import pandas as pd输出结果# create a dataframe
dataFrame = pd.DataFrame({'Product Name': ['Keyboard', 'Charger', 'SmartTV', 'Camera', 'Graphic Card', 'Earphone'],'Product Category': ['Computer', 'Mobile Phone', 'Electronics','Electronics', 'Computer', 'Mobile Phone'],'Quantity': [10, 50, 10, 20, 25, 50]})
# dataframe
print"Dataframe...\n",dataFrame
# count the observations
group = dataFrame.groupby("Product Category")
print"\nResultant DataFrame...\n",group.count()
这将产生以下输出 -
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
Resultant DataFrame...
Product Name Quantity
Product Category
Computer 2 2
Electronics 2 2
Mobile Phone 2 2
以上是 Python Pandas – 计数观察 的全部内容, 来源链接: utcz.com/z/335499.html