pivot_table自定义索引列和跨度
时间: 2023-10-15 21:02:02 浏览: 46
在使用 pivot_table 进行数据透视时,可以通过指定 index 参数来自定义索引列。例如:
```python
import pandas as pd
df = pd.DataFrame({
'name': ['Alice', 'Bob', 'Charlie', 'Alice', 'Bob', 'Charlie'],
'year': [2018, 2018, 2018, 2019, 2019, 2019],
'score': [80, 90, 85, 95, 85, 90]
})
table = pd.pivot_table(df, values='score', index=['name', 'year'])
print(table)
```
输出结果为:
```
score
name year
Alice 2018 80
2019 95
Bob 2018 90
2019 85
Charlie 2018 85
2019 90
```
在上面的例子中,我们将 name 和 year 两列作为索引列,生成了一个二级索引的透视表。
当然,你还可以通过指定 columns 参数来生成列的透视表。例如:
```python
import pandas as pd
df = pd.DataFrame({
'name': ['Alice', 'Bob', 'Charlie', 'Alice', 'Bob', 'Charlie'],
'year': [2018, 2018, 2018, 2019, 2019, 2019],
'score': [80, 90, 85, 95, 85, 90],
'subject': ['Math', 'Math', 'Math', 'English', 'English', 'English']
})
table = pd.pivot_table(df, values='score', index=['name', 'year'], columns=['subject'])
print(table)
```
输出结果为:
```
subject English Math
name year
Alice 2018 NaN 80.0
2019 95.0 NaN
Bob 2018 NaN 90.0
2019 85.0 NaN
Charlie 2018 NaN 85.0
2019 90.0 NaN
```
在上面的例子中,我们将 name 和 year 两列作为索引列,subject 列作为列的透视表。
另外,如果你想要自定义索引列的跨度,可以使用 pd.cut 函数对列进行分组,然后将分组结果作为索引列。例如:
```python
import pandas as pd
df = pd.DataFrame({
'name': ['Alice', 'Bob', 'Charlie', 'Alice', 'Bob', 'Charlie'],
'age': [20, 25, 30, 35, 40, 45],
'score': [80, 90, 85, 95, 85, 90]
})
df['age_group'] = pd.cut(df['age'], [0, 25, 30, 35, 50], labels=['<25', '25-30', '30-35', '>35'])
table = pd.pivot_table(df, values='score', index=['name', 'age_group'])
print(table)
```
输出结果为:
```
score
name age_group
Alice <25 80
>35 95
Bob 25-30 90
>35 85
Charlie 30-35 85
>35 90
```
在上面的例子中,我们使用 pd.cut 函数将 age 列分为了四个区间,并将分组结果作为索引列。可以看到,透视表中的索引列是由 name 和 age_group 两列组成的。