【问题标题】:can't plot groupby object in pandas无法在熊猫中绘制 groupby 对象
【发布时间】:2019-06-29 21:50:05
【问题描述】:

我已将 groupby 方法应用于我的数据框 df,以便在我的列 X(百分比)的每个值处获得平均值

df1 = df.groupby('percentage')['ratio'].mean()

即对于每个百分比值,我有一个比率值的平均值(因为我有很多数据点)。

现在我想绘制新的百分比 (X) 与新的比率值 (Y),但我不能。 df1[:,0] 给我一条错误消息,好像它不是我的第一列的写调用。

如何绘制这两列?

这是df1的输出:

percentage
0.000000    0.987699
0.000144    0.974359
0.000461    0.930000
0.001427    0.880549
0.006119    0.968185
0.008497    0.968686
0.017821    0.970008
0.028747    0.976759
0.030128    0.975607
0.038823    0.979795
0.043440    0.979847
Name: ratio, Length: 61, dtype: float64

【问题讨论】:

  • 你尝试了什么?
  • 我现在只是尝试访问第一列。我不明白为什么 df1.iloc[:,0] 不将第一列作为输出。你能帮忙吗?
  • 您遇到了什么错误?
  • 索引错误:IndexingError Traceback(最近一次调用最后一次) in ----> 1 df1.iloc[:,0] ~\Anaconda3\ lib\site-packages\pandas\core\indexing.py in __getitem__(self, key) 1470 except (KeyError, IndexError): 1471 pass -> 1472 return self._getitem_tuple(key) 1473 else: 1474 # 根据定义,我们只有第0轴
  • 试试:df1.reset_index().plot()

标签: python pandas matplotlib


【解决方案1】:

df1pandas.Series。通过 pandas,可以使用带有内置函数的 maplotlib,例如 pandas.plot()。你可以这样做:

import matplotlib.pyplot as plt
axes = df1.plot()
axes.set_ylabel(df1.name)
plt.show()

【讨论】:

    【解决方案2】:

    嗯,这真的很奇怪,但df1 是一个系列,而不是数据框。左边的行是系列索引,右边是值,所以print(df[0.017821]) 会打印0.970008,你仍然可以访问这些值

    percentage = list(df1.index)
    ratio = df1.values
    

    这就是您收到错误消息的原因,系列只有一个轴

    【讨论】:

      【解决方案3】:

      只需绘制df1

      import random
      import pandas as pd
      import numpy as np
      from matplotlib import pyplot as plt
      
      p = [.1,.2,.3,.4,.5,.6,.7, .8,.9]
      p = [random.choice(p) for _ in range(180)]
      r = np.linspace(.001, .999, num=180)
      
      df = pd.DataFrame({'pct':p, 'ratio':r})
      df1 = df.groupby('pct')['ratio'].mean()
      df1.plot()
      plt.show()
      plt.close()
      

      【讨论】:

      • 错字:np.random
      【解决方案4】:

      您无法访问特定列,因为您处理的是系列而不是数据框。

      type(df.groupby('percentage')['ratio'].mean())
      # pandas.core.series.Series
      

      我认为.reset_index() 应该会有所帮助,因为它将您的结果转换为数据框

      type(df.groupby('percentage')['ratio'].mean().reset_index())
      # pandas.core.frame.DataFrame
      

      所以,一旦您使用.reset_index(),您就可以将列分配给变量:

      new_df = df.groupby('percentage')['ratio'].mean().reset_index()
      x, y = (new_df['percentage'], new_df['ratio'])
      

      【讨论】:

        猜你喜欢
        • 2016-04-21
        • 2020-03-25
        • 1970-01-01
        • 2019-02-24
        • 2017-12-31
        • 2018-09-26
        • 2018-07-09
        • 2019-03-20
        • 2015-02-04
        相关资源
        最近更新 更多