python数据透视表筛选
时间: 2023-10-09 09:11:33 浏览: 34
使用Python进行数据透视表筛选可以使用Pandas库中的pivot_table()方法。下面是一个简单的例子:
假设我们有一个数据集,包含销售数据,其中包含产品、销售日期和销售额。
```
import pandas as pd
data = {'product': ['A', 'B', 'C', 'A', 'B', 'C', 'A', 'B', 'C'],
'date': ['2021-01-01', '2021-01-01', '2021-01-01', '2021-01-02', '2021-01-02', '2021-01-02', '2021-01-03', '2021-01-03', '2021-01-03'],
'sales': [100, 200, 150, 300, 250, 200, 150, 100, 50]}
df = pd.DataFrame(data)
print(df)
```
输出结果如下:
```
product date sales
0 A 2021-01-01 100
1 B 2021-01-01 200
2 C 2021-01-01 150
3 A 2021-01-02 300
4 B 2021-01-02 250
5 C 2021-01-02 200
6 A 2021-01-03 150
7 B 2021-01-03 100
8 C 2021-01-03 50
```
现在,我们可以使用pivot_table()方法来创建一个数据透视表,并根据需要进行筛选。例如,我们可以按产品和日期进行分组,并计算销售总额:
```
pivot_table = pd.pivot_table(df, index=['product', 'date'], values='sales', aggfunc='sum')
print(pivot_table)
```
输出结果如下:
```
sales
product date
A 2021-01-01 100
2021-01-02 300
2021-01-03 150
B 2021-01-01 200
2021-01-02 250
2021-01-03 100
C 2021-01-01 150
2021-01-02 200
2021-01-03 50
```
现在,如果我们只想查看产品A的销售数据,我们可以使用.loc[]方法进行筛选:
```
pivot_table_A = pivot_table.loc['A']
print(pivot_table_A)
```
输出结果如下:
```
sales
date
2021-01-01 100
2021-01-02 300
2021-01-03 150
```
同样,如果我们只想查看2021年1月1日的销售数据,我们可以使用.loc[]方法进行筛选:
```
pivot_table_jan1 = pivot_table.loc[(slice(None), '2021-01-01'), :]
print(pivot_table_jan1)
```
输出结果如下:
```
sales
product date
A 2021-01-01 100
B 2021-01-01 200
C 2021-01-01 150
```
以上就是使用Python进行数据透视表筛选的示例。您可以根据需要进行修改和扩展。
相关推荐
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.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_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.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)