根据唯一时间对 pandas datafreme 列进行分组

问题描述 投票:0回答:1

我有一个数据框,包括数据时间和数值数据。 我只想离开几个小时。因为我想根据时间和Sayi绘制直方图图形。 我能怎么做? 我的代码是这样的

import pandas as pd
import matplotlib.pyplot as plt
from datetime import datetime as dt

df = pd.read_excel(r"C:\Users\cem.aydemir\Documents\PYTHON\Ocak_Nakliye.xlsx")
df['Sayi'] = df['NET']
df = df[['Zaman' , 'Sayi']]
df['Zaman'] = pd.to_datetime(df['Zaman'], 
                                    format='%H:%M:%S')
df['Zaman'] = (df.Zaman - df.Zaman.dt.normalize()).dt.floor('5T')

df = df.groupby([pd.Grouper(key= 'Zaman', 
                               freq= 'h')])['Sayi'].count().reset_index()
df = df[df['Sayi'] > 0]
x =df['Zaman']
y= df['Sayi']
plt.figure(figsize=(15,8))
plt.plot(x,y)
plt.show()
pd.options.display.min_rows = 20
print(df)

并输出: 扎曼萨伊 0 0 天 00:00:00 4 8 0 天 08:00:00 142 9 0 天 09:00:00 2600 10 0 天 10:00:00 3997 11 0 天 11:00:00 3345 12 0 天 12:00:00 3217 13 0 天 13:00:00 1395 14 0 天 14:00:00 2203 15 0 天 15:00:00 2913 16 0 天 16:00:00 3869 17 0 天 17:00:00 3655 18 0 天 18:00:00 1893 19 0 天 19:00:00 218 20 0 天 20:00:00 37 21 0 天 21:00:00 12 22 0 天 22:00:00 9 23 0 天 23:00:00 1

我尝试根据时间进行分组。但Python正在摸索日期。所以,我尽量只留下时间。但 Python 输出的时间为“0 天”。我只想看到时间却做不到。

time grouping
1个回答
0
投票

他的代码是正确的,但是有一个小修复可以让分组的时间合适。

秘诀如下:

Python df['Zaman'] = pd.to_datetime(df['Zaman']).dt.time # 仅从 'Zaman' 中提取时间 谨慎使用代码。 该行仅抓取“Zaman”列中的时间部分。然后,您可以像以前一样按小时分组。这将为您提供直方图所需的每小时计数!

© www.soinside.com 2019 - 2024. All rights reserved.