pandas将表里的数值按照区间进行替换并绘制饼图
时间: 2024-05-23 10:04:17 浏览: 7
可以使用 pandas.cut() 方法将数值按照区间进行分组,并使用 value_counts() 方法统计每个区间的数量,最后使用 plot.pie() 方法绘制饼图。以下是代码示例:
```python
import pandas as pd
import matplotlib.pyplot as plt
# 创建示例数据
df = pd.DataFrame({'score': [78, 85, 95, 62, 56, 72, 88, 90, 68, 75, 82, 91, 84, 79, 63, 70, 76, 92, 87, 81]})
# 将分数按照区间分组
bins = [0, 60, 70, 80, 90, 100]
labels = ['不及格', '及格', '良好', '优秀', '完美']
df['category'] = pd.cut(df['score'], bins=bins, labels=labels)
# 统计每个区间的数量
counts = df['category'].value_counts()
# 绘制饼图
plt.figure(figsize=(6, 6))
counts.plot.pie(autopct='%1.1f%%', labels=labels)
plt.title('分数区间分布')
plt.show()
```
输出结果为:
![pie_chart.png](https://cdn.jsdelivr.net/gh/Yanhua-Wu/image-hosting/images/pie_chart.png)
相关问题
如何用python 把excel的某一列数据按照区间分组并绘制饼图
可以使用 Pandas 和 Matplotlib 库来完成此任务。
首先,需要安装 Pandas 和 Matplotlib 库:
```
pip install pandas
pip install matplotlib
```
接下来,可以使用 Pandas 读取 Excel 文件,将数据加载到 DataFrame 中:
```python
import pandas as pd
df = pd.read_excel('data.xlsx')
```
假设要对 DataFrame 中的 "score" 列数据进行分组并绘制饼图。可以使用 Pandas 的 cut 方法将数据按照区间分组:
```python
# 定义分组边界
bins = [0, 60, 70, 80, 90, 100]
# 将数据按照分组边界分组
df['group'] = pd.cut(df['score'], bins)
# 统计每个分组的数量
group_count = df['group'].value_counts()
```
接下来,可以使用 Matplotlib 绘制饼图:
```python
import matplotlib.pyplot as plt
# 绘制饼图
plt.pie(group_count, labels=group_count.index, autopct='%1.1f%%')
plt.title('Score Distribution')
plt.show()
```
完整代码如下:
```python
import pandas as pd
import matplotlib.pyplot as plt
# 读取 Excel 文件
df = pd.read_excel('data.xlsx')
# 定义分组边界
bins = [0, 60, 70, 80, 90, 100]
# 将数据按照分组边界分组
df['group'] = pd.cut(df['score'], bins)
# 统计每个分组的数量
group_count = df['group'].value_counts()
# 绘制饼图
plt.pie(group_count, labels=group_count.index, autopct='%1.1f%%')
plt.title('Score Distribution')
plt.show()
```
请注意,此示例代码仅供参考,实际应用中需要根据数据格式和需求进行适当修改。
读取csv并将年份弄成区间绘制饼图
好的,我可以为您提供 Python 代码来实现这个功能。首先,您需要安装 pandas 和 matplotlib 这两个 Python 库,可使用以下命令进行安装:
```
pip install pandas matplotlib
```
接下来,您可以使用以下代码读取 CSV 文件并将年份转换为年份区间:
```python
import pandas as pd
# 读取 CSV 文件
df = pd.read_csv('data.csv')
# 将年份转换为年份区间
df['year_range'] = pd.cut(df['year'], bins=[1900, 1920, 1940, 1960, 1980, 2000, 2020], labels=['1900-1920', '1920-1940', '1940-1960', '1960-1980', '1980-2000', '2000-2020'])
```
然后,您可以使用以下代码绘制饼图:
```python
import matplotlib.pyplot as plt
# 按年份区间计算数据
data = df['year_range'].value_counts()
# 绘制饼图
plt.pie(data, labels=data.index, autopct='%1.1f%%')
plt.title('Year Range Distribution')
plt.show()
```
这将绘制一个饼图,显示年份区间分布情况。您可以根据需要调整代码以满足特定需求。