GroupBy 对象
pandas 库的 GroupBy 对象是一个存储容器,用于将 DataFrame 行分组到存储桶中。它提供了一组方法来聚合和分析集合中的每个独立组。它允许我们提取每个组中特定索引位置的行。它还提供了一种迭代行组的便捷方法。
import pandas as pd
从头开始创建 GroupBy 对象
我们首先创建一个 DataFrame 来存储超市中水果和蔬菜的价格:
>>> import pandas as pd
>>> food_data = {
... "Item": ["Banana", "Cucumber", "Orange", "Tomato", "Watermelon"],
... "Type": ["Fruit", "Vegetable", "Fruit", "Vegetable", "Fruit"],
... "Price": [0.99, 1.25, 0.25, 0.33, 3.00],
... }
>>> supermarket = pd.DataFrame(data=food_data)
>>> supermarket
Item Type Price
0 Banana Fruit 0.99
1 Cucumber Vegetable 1.25
2 Orange Fruit 0.25
3 Tomato Vegetable 0.33
4 Watermelon Fruit 3.00
>>>
GroupBy 对象根据列中的共享值将 DataFrame 行组织到存储桶中。假设我们对水果的平均价格和蔬菜的平均价格感兴趣。如果我们可以将“水果”行和“蔬菜”行分离到不同的组中,则执行计算会更容易。
让我们首先在 supermarket DataFrame 上调用 groupby
方法。我们需要向它传递一个列,pandas 将使用该列的值来创建组,该方法返回一个 GroupBy
。GroupBy
对象与 DataFrame 是独立且不同的:
>>> groups = supermarket.groupby("Type")
>>> groups
<pandas.core.groupby.generic.DataFrameGroupBy object at 0x0000013B98496290>
>>>
get_group
方法接受组名称并返回包含相应行的 DataFrame。
>>> groups.get_group("Fruit")
Item Type Price
0 Banana Fruit 0.99
2 Orange Fruit 0.25
4 Watermelon Fruit 3.00
>>> groups.get_group("Vegetable")
Item Type Price
1 Cucumber Vegetable 1.25
3 Tomato Vegetable 0.33
>>>
GroupBy 对象擅长聚合操作,比如很容易计算每组数值列的均值。
>>> groups.mean(numeric_only=True)
Price
Type
Fruit 1.413333
Vegetable 0.790000
>>>
从数据集中创建 GroupBy 对象
Fortune1000.csv
文件是 2018 年财富 1000 强公司的集合。每行包括公司名称、收入、利润、员工人数、领域和行业:
>>> fortune = pd.read_csv('../data/fortune1000.csv')
>>> fortune
Company Revenues Profits Employees Sector Industry
0 Walmart 500343.0 9862.0 2300000 Retailing General Merchandisers
1 Exxon Mobil 244363.0 19710.0 71200 Energy Petroleum Refining
2 Berkshire Hathaway 242137.0 44940.0 377000 Financials Insurance: Property and Casualty (Stock)
3 Apple 229234.0 48351.0 123000 Technology Computers, Office Equipment
4 UnitedHealth Group 201159.0 10558.0 260000 Health Care Health Care: Insurance and Managed Care
.. ... ... ... ... ... ...
995 SiteOne Landscape Supply 1862.0 54.6 3664 Wholesalers Wholesalers: Diversified
996 Charles River Laboratories Intl 1858.0 123.4 11800 Health Care Health Care: Pharmacy and Other Services
997 CoreLogic 1851.0 152.2 5900 Business Services Financial Data Services
998 Ensign Group 1849.0 40.5 21301 Health Care Health Care: Medical Facilities
999 HCP 1848.0 414.2 190 Financials Real estate
[1000 rows x 6 columns]
>>>
一个领域可以有很多公司。例如,Apple 和 Amazon.com 都属于 “Technology” 行业。行业是领域内的子类别。例如,“Pipelines” 和 “Petroleum Refining” 行业属于 “Energy” 行业。
加入想要知道某个领域的平均收入,可以这样:
>>> retailing_mask = fortune["Sector"] == "Retailing"
>>> retail_companies = fortune[retailing_mask]
>>> retailing_mask.head()
0 True
1