【问题标题】:Python: How to Filter Pandas Dataframe and plot incremental valuesPython:如何过滤 Pandas 数据框并绘制增量值
【发布时间】:2021-11-04 11:42:21
【问题描述】:

我在分组数据和随时间绘制以显示增量变化时遇到问题。 传入数据中的数据结构如下,并添加到 pandas 数据帧中:

“日期时间”、“分类”、“置信度”

我想要做的是显示分类的唯一值并计算它们每 5 分钟出现的次数。 然后,我想将其绘制在一个图表中,该图表将每 5 分钟更新一次,显示随时间推移的增量值。

我尝试了不同的方法,但我无法理解它。我能得到的数据框是:

Index class count
0 Car 2
1 Truck 1
2 Boat 3

我得到了“索引”、“类”、“计数” 我可以每 5 分钟更新一次,也可以将其添加到包含 'TimeStamp','Dataframe',其中数据帧如上所示。

我想要的图表中的输出是每个类以不同颜色显示的一行,每 5 分钟显示它们在数据框中的数量。

如何在 python 中使用 pandas 和 matplotlib 来做到这一点? 我在下面附上我的垃圾代码只是为了展示我一直在使用的东西 起点……

支持最受重视

def CreateStats():
print("Reading from file")
fo  = open("/home/User/Temp/test_data.txt", "r")    
df = pd.DataFrame(columns=['time', 'class', 'conf'])
ndf = pd.DataFrame(columns=['class', 'class count'])
pos = 0
nPos=0
for t in range(1):
    fo.seek(0, 0)
    for line in fo:            
        #print(str(datetime.now())+" - " + line)
        #time.sleep(1)        
        splitted = line.split(";")
        df.loc[pos] = [datetime.now().strftime("%Y-%m-%d %H:%M:%S"),splitted[0],right(splitted[1],1)]        
        pos=pos+1
    #time.sleep(1)
    df['time'] = pd.to_datetime(df['time'])
    ndf = df.groupby('class').agg({'class':['count']}).reset_index()
    #ndf = df.groupby('class').count().reset_index()
    #ndf = df.groupby('class').agg('count').reset_index()
                    
    #print(df.head())
    #newDf = [datetime.now(),ndf]
    print(ndf)
    #ndf.plot.scatter(x='class', y='time count')
    #plt.show()
    
fo.close()

【问题讨论】:

  • 您是否尝试过使用matplotlib.pyplot.plot?此外,使用简单的dict 将类映射到计数可能比数据框更容易。
  • 我使用matplotlib(我认为)或者它实际上是熊猫情节?我将尝试使用 matplotlib 来查看情节是否更容易。但是数据框是否存在。我不知道如何创建数据结构来获取增量值并绘制每个类。
  • 这是我的意思的一个例子link
  • 和这个非常相似:stackoverflow.com/questions/66934662/… 但我不明白
  • 现在我将其作为聚合数据框。所以每一列 0,1,2,3,4,5 等都是时间戳 { 0 1 2 3 4, Bubbles 10 10 10 10 10, Undefined 10 10 10 10 10, Melt Defects 5 5 5 5 5}

标签: python pandas dataframe matplotlib group-by


【解决方案1】:

我找到了办法。也许不是 python 方式:

def CreateStats():
    print("Reading from file")    
    aggDict = {}
    fo  = open("/home/user/Temp/test_data.txt", "r") 
    for t in range(20):        
        fo.seek(0, 0)
        aggDict[t] = defaultdict(int)
        for line in fo:
            #print(str(datetime.now())+" - " + line)
            defect = line.split(";")
            aggDict[t][defect[0]] += 1           
            if t > 0:
                for key in aggDict[t]:
                    aggDict[t][key] += aggDict[t-1][key]
    print(aggDict)
    df = pd.DataFrame(aggDict)
    df2 = df.transpose()
    lines = df2.plot.line()
    plt.show()

{
0: defaultdict(, { 'Bubbles': 2, 'Rabbits': 2, 'Cup': 1}),
1: defaultdict(, {'Bubbles': 12, 'Rabbits': 10, 'Cup': 2}),
2: defaultdict(, {'Bubbles': 62, 'Rabbits': 42, 'Cup': 3})
}

使用的文件包含一个 2 列分号;类型和值的分隔列表。未使用此代码中的值...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-09-29
    • 2019-12-12
    • 2019-01-30
    • 2017-02-21
    • 2018-09-29
    • 2018-06-07
    • 2018-03-08
    • 2019-09-24
    相关资源
    最近更新 更多