df.groupby('subject').apply(mean)NameError: name 'mean' is not defined
时间: 2023-10-02 20:05:38 浏览: 54
The error message you received indicates that Python does not recognize the name `mean`. This is because the `mean` function needs to be imported from the `numpy` or `pandas` library in order to use it.
Here's an example of how you can use `mean` in the context of a `groupby` operation in `pandas`:
```python
import pandas as pd
# create a dataframe
df = pd.DataFrame({
'subject': ['Math', 'Math', 'Science', 'Science'],
'score': [85, 92, 78, 80]
})
# calculate the mean score for each subject
mean_scores = df.groupby('subject')['score'].mean()
print(mean_scores)
```
Output:
```
subject
Math 88.5
Science 79.0
Name: score, dtype: float64
```
Note that `mean` is called as a method on the `score` column of the grouped dataframe, not as a standalone function.
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![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)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)