我正在熊猫的一个数据框中工作,就像这样。
Identifier datetime
0 AL011851 00:00:00
1 AL011851 06:00:00
2 Al011851 12:00:00
到目前为止,这是我的代码:
import pandas as pd
hurricane_df = pd.read_csv("hurdat2.csv",parse_dates=['datetime'])
hurricane_df['datetime'] = pd.to_timedelta(hurricane_df['datetime'].dt.strftime('%H:%M:%S'))
hurricane_df
grouped = hurricane_df.groupby('datetime').size()
grouped
我所做的是将datetime列转换为timedelta以获取小时数。我想获取datetime列的大小,但是我只想要1:00、2:00、3:00等小时,但是我得到的是分钟间隔,例如1:15和2:45。
有什么办法可以显示小时? 谢谢。
答案 0 :(得分:0)
df = pd.DataFrame({'Identifier':['AL011851','AL011851','AL011851'],'datetime': ["2018-12-08 16:35:23","2018-12-08 14:20:45", "2018-12-08 11:45:00"]})
df['datetime'] = pd.to_datetime(df['datetime'])
df
Identifier datetime
0 AL011851 2018-12-08 16:35:23
1 AL011851 2018-12-08 14:20:45
2 AL011851 2018-12-08 11:45:00
# Rounds to nearest hour
def roundHour(t):
return (t.replace(second=0, microsecond=0, minute=0, hour=t.hour)
+timedelta(hours=t.minute//30))
df.datetime=df.datetime.map(lambda t: roundHour(t)) # Step 1: Round to nearest hour
df.datetime=df.datetime.map(lambda t: t.strftime('%H:%M')) # Step 2: Remove seconds
df
Identifier datetime
0 AL011851 17:00
1 AL011851 14:00
2 AL011851 12:00
答案 1 :(得分:0)
您可以通过const translate = str => console.log(
str.match(/(?! )(?:[^",]+|"[^"]*")+/g)
);
[
`12.0,trs,"xx-xx NY,US"`,
`"12.0","trs","xx-xx NY,US"`,
`"12.0","trs", "xx-xx NY,US"`
].forEach(translate);
快捷方式使用pandas.Timestamp.round
:
Series.dt
所以
df['datetime'] = df['datetime'].dt.round('h')
成为
... datetime
01:15:00
02:45:00