【问题标题】:Plot a chart depending on price and date根据价格和日期绘制图表
【发布时间】:2021-12-17 04:49:07
【问题描述】:

我有问题。我有一个数据框(请参见下文)。其中包含价格和日期。我想显示每个月的平均价格。我怎么能这样做?我试过了,但我得到了以下错误KeyError: 'month'。如何绘制如下图?

   listing_id       date  price  month  year
0           1 2021-09-07  79.00      9  2021
1           2 2021-08-07  80.00      8  2021
2           3 2021-06-07  90.00      6  2021
3           4 2021-06-05  20.00      6  2021
d = {'listing_id': [1, 2, 3, 4],
     'date': ['2021-09-07', '2021-08-07', '2021-06-07', '2021-06-05'],
     'price': ['$79.00', '$80.00', '$90.00', '$20.00']}
df = pd.DataFrame(data=d)
df['price'] = df['price'].str.replace('$', '', regex=False)
df['date'] = pd.to_datetime(df['date'])
df['month'], df['year'] = df.date.dt.month, df.date.dt.year
print(df)

x = df['month'].unique()
y = df.groupby('date').avg()[['price']]

plt.plot(x,y)
plt.show()

KeyError: 'month'

【问题讨论】:

  • df.groupby('month')['price'].mean().plot()
  • 在绘图之前不要忘记将price 转换为浮点数
  • 它应该是条形图而不是线图。 df.groupby('month')['price'].mean().plot(kind='bar', rot=0)
  • 根据@QuangHoang df['price'] = df['price'].str.replace('$', '', regex=False).astype(float)

标签: python pandas dataframe matplotlib


【解决方案1】:

不确定以下内容是对您问题的回答。 反正...

  1. 添加了另一年的一些数据。在问题'平均价格 每个月'对于如何考虑这一点不够精确
  2. 按照 Trenton McKinney 绘制条形图。但为缺失月份引入 0 值会更合适。
import pandas as pd

d = {'listing_id': [1, 2, 3, 4, 5, 6],
     'date': ['2022-09-07', '2022-08-07', 
              '2021-09-07', '2021-08-07', '2021-06-07', '2021-06-05'],
     'price': ['$79.00', '$85.00','$79.00', '$80.00', '$90.00', '$20.00']}

df = pd.DataFrame(data=d)
df['price'] = df['price'].str.replace('$', '', regex=False).astype(float)
df['date'] = pd.to_datetime(df['date'])

(df.groupby([df.date.dt.year, df.date.dt.month])['price']
 .mean()
 .plot(kind = 'bar',
       rot = 0,
       xlabel = '(year, month)',
       ylabel = 'price')
)

【讨论】:

    【解决方案2】:

    您应该将价格列转换为数值类型以便计算其平均值,然后在df 上执行按月分组。

    正如@Trenton 指出的那样,您应该制作条形图而不是线图。

    df['price'] = df['price'].astype('float')
    df.groupby('month')['price'].mean().plot(kind='bar', rot=0)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-15
      • 1970-01-01
      • 2021-03-23
      • 1970-01-01
      相关资源
      最近更新 更多