Pandas中如何对指定的定类数据的各类进行指定的定量均值处理
时间: 2024-03-04 09:51:13 浏览: 18
要对 Pandas 数据框中的指定分类数据进行定量均值处理,可以使用 Pandas 库的 `groupby()` 方法和 `transform()` 方法。下面是一个例子:
```python
import pandas as pd
# 创建一个数据框
df = pd.DataFrame({
'name': ['Alice', 'Bob', 'Charlie', 'David', 'Emily', 'Frank'],
'gender': ['female', 'male', 'male', 'male', 'female', 'male'],
'age': [25, 20, 30, 18, 22, 28],
'salary': [5000, 4000, 6000, 3500, 4500, 7000]
})
# 对 'gender' 列进行分组,并计算每个分组的 'salary' 列的平均值
df['mean_salary'] = df.groupby('gender')['salary'].transform('mean')
print(df)
```
输出结果如下:
```
name gender age salary mean_salary
0 Alice female 25 5000 4750
1 Bob male 20 4000 4833
2 Charlie male 30 6000 4833
3 David male 18 3500 4833
4 Emily female 22 4500 4750
5 Frank male 28 7000 4833
```
在上面的例子中,我们首先创建了一个数据框 `df`,然后使用 `groupby()` 方法对 `gender` 列进行分组,接着使用 `transform()` 方法计算每个分组的 `salary` 列的平均值,并将结果存储在 `mean_salary` 列中。最后,我们输出整个数据框 `df`。
在此例中,我们对 `gender` 列进行了分组,在每个分组中计算了 `salary` 列的平均值,并将结果存储在 `mean_salary` 列中。
相关推荐
![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_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)
![](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)