读取excel的数据,然后在python用折线图表现不同年龄段(按照 [0-18,18- 40,40- 60,60- 100]分组)的人数
时间: 2023-11-28 18:51:07 浏览: 46
可以使用pandas和matplotlib库来实现这个需求。首先需要安装这两个库:
```
pip install pandas matplotlib
```
然后,读取Excel数据可以使用pandas的read_excel函数。假设Excel表格中有一个名为data的工作表,可以使用如下代码读取:
```python
import pandas as pd
df = pd.read_excel('data.xlsx', sheet_name='data')
```
接下来,我们需要将年龄分组并计算每个组的人数。可以使用pandas的cut函数来实现:
```python
bins = [0, 18, 40, 60, 100]
labels = ['0-18', '18-40', '40-60', '60-100']
df['age_group'] = pd.cut(df['age'], bins=bins, labels=labels)
grouped = df.groupby('age_group').size()
```
最后,我们可以使用matplotlib库来绘制折线图:
```python
import matplotlib.pyplot as plt
plt.plot(grouped.index, grouped.values)
plt.show()
```
完整代码如下:
```python
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_excel('data.xlsx', sheet_name='data')
bins = [0, 18, 40, 60, 100]
labels = ['0-18', '18-40', '40-60', '60-100']
df['age_group'] = pd.cut(df['age'], bins=bins, labels=labels)
grouped = df.groupby('age_group').size()
plt.plot(grouped.index, grouped.values)
plt.show()
```
注意,这里的数据仅供参考,实际使用时需要根据具体情况调整代码。