【问题标题】:How to create a plot a new DataFrame based on another Dataframe如何基于另一个数据框创建一个新的数据框
【发布时间】:2020-04-12 19:25:05
【问题描述】:

所以我有这种类型的数据框:

     Time  Type
1      81  sell
4       9  sell
7      36  sell
10     82   buy
13    106   buy
..    ...   ...
722   105  sell
723   105  sell
727   110  sell
728   110  sell
729   110  sell

Time 显示一周中的小时,Type 显示操作(买入或卖出)。我想在多条形图上绘制一个图表,其中 X 是一周中从 1 到 140 的小时数,Y 是该时间段内的买卖计数。我该怎么做?

【问题讨论】:

    标签: python pandas dataframe matplotlib plot


    【解决方案1】:

    如果我理解正确,

    df.groupby(['Time']).apply(lambda x: x['Type'].value_counts()).plot(kind='bar')
    

    或者如果你想要酒吧彼此相邻。

    df = df.groupby(['Time']).apply(lambda x: x['Type'].value_counts())
    df.reset_index().pivot('Time','level_1','Type').plot(kind='bar')
    

    【讨论】:

    • 我收到此错误:TypeError: no numeric data to plot 当我尝试 df.groupby(['Time', 'Type']).count() 我得到一个元组列表,例如:索引: [(0, 卖), (2, 买), (4, 买), (5, 买)....]
    • 元组列表?
    • 当我输入 df = df.groupby(['Time','Type']).count() 并且当我打印它时,我得到了这个prnt.sc/rxr3na
    • prnt.sc/rxra4p 我已经到了这一点。现在,我如何绘制它以便得到 X=Time 和 Y=Buys,Sells ?
    • 我不明白 level_1 代表什么?以及如何更改该变量,因为当我更改它时会出现错误
    【解决方案2】:

    使用我的方法,我为买卖计数创建了两个新列,然后按时间和类型分组。然后我创建了一个情节。

    import numpy as np
    import pandas as pd
    import matplotlib.pyplot as plt
    df1=df.copy()
    df1['Type_Count_Sell'] = np.where(df1['Type'] == 'sell', 1, 0)
    df1['Type_Count_Buy'] = np.where(df1['Type'] == 'buy', 1, 0)
    df1=df1.groupby(['Time', 'Type']).sum().reset_index()
    #df1=df1.loc[df1.Time != '...']
    df1['Time']=df1['Time'].astype(int)
    
    ax = plt.subplot(111)
    ax.set_title('Buys an dSells Count')
    ax.set_xlabel('Hour')
    ax.set_ylabel('Count of Type')
    ax.bar(df1['Time'], df1['Type_Count_Sell'], width=1, color='b', align='center')
    ax.bar(df1['Time']+1, df1['Type_Count_Buy'], width=1, color='g', align='center')
    plt.show()
    

    【讨论】:

    • 这行得通。但由于某种原因,它绘制了相同数量的买卖,而我的数据框中并非如此。为什么会发生这种情况?
    • @blennd 我用编辑“将 groupby 更改为 sum 而不是 count,这是一个错误”更新了我的答案。我还将条形的宽度从 0.2 增加到 1。
    猜你喜欢
    • 1970-01-01
    • 2019-02-02
    • 2018-05-20
    • 1970-01-01
    • 2016-05-07
    • 1970-01-01
    • 1970-01-01
    • 2023-04-09
    • 1970-01-01
    相关资源
    最近更新 更多