如何在pandas中将两年行合并为范围,并用另一列绘制其图形

2024-09-29 23:25:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个数据集,包含ageFrom、ageTo和sales列。现在我想画一个图,在一个轴上显示年龄范围,在另一个轴上显示销售额,以根据年龄范围计算销售额

enter image description here

我已按年龄从、年龄到分组,并找到了销售额的总和。现在我需要在x轴上绘制ageFrom和ageTo作为范围,在Y轴上绘制总量。如何处理这个问题


Tags: 数据绘制sales年龄总和销售额总量agefrom
1条回答
网友
1楼 · 发布于 2024-09-29 23:25:34

现在我不确定你有/没有尝试过什么,但是最简单的方法是为你的范围创建一个平均值列(如果你想创建一个范围,避免使用非数值),然后根据你的销售额绘制它。以下各项应能做到这一点:

import pandas as pd

#data
d = {'ageFrom': [0, 11, 21, 31], 'ageTo': [10, 20, 30, 40], 'sales':[2, 10, 15, 20]}
#create dataframe
df = pd.DataFrame(data = d)

#create a mean value for your range
df['mean'] = (df['ageFrom']  + df['ageTo'])/2
#plot data
ax1 = df.plot.scatter(x='mean',y='sales')

enter image description here

或:您仍然可以创建范围列并将其绘制为条形图,如下所示:

#create a range column
df['range'] = df['ageFrom'].astype(str)  + '-' + df['ageTo'].astype(str)
#plot bar
ax2 = df.plot.bar(x='range', y='sales', rot=0)

enter image description here

最后您仍然可以使用matplotlib为x轴使用非数字,如下所示:

import matplotlib.pyplot as plt

plt.scatter(df.range,df['sales'],c='b',label='range')

enter image description here

相关问题 更多 >

    热门问题