【发布时间】: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