pandas groupby multicolumns
时间: 2023-12-14 08:02:38 浏览: 31
To group by multiple columns in pandas, you can pass a list of column names to the groupby() method. Here's an example:
``` python
import pandas as pd
# create a sample dataframe
data = {'group': ['A', 'A', 'B', 'B', 'B'],
'year': [2018, 2018, 2019, 2019, 2020],
'value': [10, 15, 20, 25, 30]}
df = pd.DataFrame(data)
# group by 'group' and 'year' columns and calculate the sum of 'value'
grouped = df.groupby(['group', 'year'])['value'].sum()
print(grouped)
```
Output:
```
group year
A 2018 25
B 2019 45
2020 30
Name: value, dtype: int64
```
In this example, we grouped the dataframe by the 'group' and 'year' columns and calculated the sum of the 'value' column for each group. The resulting object is a pandas series with a hierarchical index, where the first level corresponds to the 'group' column and the second level corresponds to the 'year' column.
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)