我正在学习pandas
,并且具有很强的SQL背景,因此我需要重新考虑许多习惯和思维方式。虽然我认为我了解groupby()
方法,但是我仍然无法弄清楚如何将其应用于多个列。
假设我们在数据库中有此表:
+----+--------------+-----------+--------------+-------+
| id | product_name | category | subcategory | price |
+----+--------------+-----------+--------------+-------+
| 1 | product1 | category1 | subcategory1 | 8.41 |
| 2 | product2 | category1 | subcategory1 | 62.74 |
| 3 | product3 | category1 | subcategory2 | 85.84 |
| 4 | product4 | category2 | subcategory2 | 32.71 |
| 5 | product5 | category2 | subcategory1 | 39.62 |
| 6 | product6 | category2 | subcategory1 | 37.43 |
| 7 | product7 | category3 | subcategory2 | 55.01 |
| 8 | product8 | category3 | subcategory1 | 26.91 |
| 9 | product9 | category3 | subcategory3 | 77.13 |
| 10 | product10 | category3 | subcategory3 | 40.79 |
+---+--------------+-----------+--------------+-------+
在多个列上进行汇总非常容易:
select category, subcategory, avg(price) as avg_price from my_table group by category, subcategory
返回以下内容:
+-----------+--------------+-----------+
| category | subcategory | avg_price |
+-----------+--------------+-----------+
| category1 | subcategory1 | 35.575 |
| category1 | subcategory2 | 85.84 |
| category2 | subcategory1 | 38.525 |
| category2 | subcategory2 | 32.71 |
| category3 | subcategory1 | 26.91 |
| category3 | subcategory2 | 55.01 |
| category3 | subcategory3 | 58.96 |
+-----------+--------------+-----------+
因此,以我显然不正确的理解,这在大熊猫中也是如此:
df['price'].groupby(df[['category', 'subcategory']]).mean()
返回ValueError: Grouper for '<class 'pandas.core.frame.DataFrame'>' not 1-dimensional
,而:
df['price'].groupby(df['category']).mean()
按预期工作。
有人可以帮我吗?
答案 0 :(得分:1)
我认为您需要-
df.groupby(['category', 'subcategory'])['price'].mean()
答案 1 :(得分:0)
您必须修改groupby
语法
df.groupby(['category', 'subcategory'])['price'].mean()