【问题标题】:How to convert time into specific format in python?如何在python中将时间转换为特定格式?
【发布时间】:2021-06-06 04:57:59
【问题描述】:

我的 pandas DataFrame 中有一个时间列,包含超过 800,000 行。时间格式是这样的:

08:28:31
08:28:35
08:28:44
08:28:44

我想将此格式转换为每小时,这意味着如果第一次是 08:28:31,那么第二次时间应该是每小时 09:28:31 等。我们如何在 python 中实现这一点使用 DateTime 库

输出数据:

08:28:31
09:28:31
...
23:28:31

08:28:35
09:28:35
...
23:28:35

08:28:44
...
08:28:44
...

【问题讨论】:

标签: python pandas datetime time rows


【解决方案1】:

用途:

#convert values to datetimes
df['date'] = pd.to_datetime(df['date'])

#count number of repeated values
df = df.loc[df.index.repeat(24 - df['date'].dt.hour)]
#generate hour timedeltas
hours = pd.to_timedelta(df.groupby(level=0).cumcount(), unit='H')

#add to dates and generate times with convert index to default values
s = df['date'].add(hours).dt.time.reset_index(drop=True)
print (s)
0     08:28:31
1     09:28:31
2     10:28:31
3     11:28:31
4     12:28:31
  
59    19:28:44
60    20:28:44
61    21:28:44
62    22:28:44
63    23:28:44
Length: 64, dtype: object

【讨论】:

  • 如果我们想在每 15 分钟后抽出时间怎么办。有可能吗?
  • @OfficialDeveloper - 你可以尝试将hours = pd.to_timedelta(df.groupby(level=0).cumcount(), unit='H') 更改为hours = pd.to_timedelta(df.groupby(level=0).cumcount(), unit='Min') * 15 吗?
  • 正如你告诉我使用 df.groupby('Time', as_index=False)['Price'].mean() ,如果发生重复,我必须只取重复行的平均值不是整列
  • @OfficialDeveloper - 是的,但如果使用 mean 的不重复值相同,那么解决方案运行良好。
猜你喜欢
  • 2022-11-16
  • 1970-01-01
  • 2020-04-12
  • 2023-03-27
  • 2017-08-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多