【问题标题】:Converting Object to Time in python Pandas在 python Pandas 中将对象转换为时间
【发布时间】:2021-08-16 05:33:28
【问题描述】:

我有一个数据集,其中包含一个包含“时间”值的列,但它显示为对象,我想将它们转换为时间,以便我可以执行一个 for 循环来查看时间是否在两次之间。

for i in df['Time']:
    if i >= dt.time(21,0,0) and i <= dt.time(7, 30,0) or i >= dt.time(3,0,0) and i <= dt.time(10,0,0) or i >= dt.time(10,30,0) and i <= dt.time(14,0,0):
        df['In/Out'] = 'In'
    else:
        df['In/Out'] = 'Out'

如果时间介于两次之间,我希望代码将新列中的值设置为“In”。 第一次是 (21:00) & (07:30) 第二次是 (03:00) & (10:00) 第三次是 (10:30) & (14:00)

如果时间不在这些范围内,则应将新列中的值设置为“Out”。

【问题讨论】:

  • 请提供最少的可重现数据,或者您可以发布 Dataframe 以获得正确的建议。同时,你可以试试df['Time'] = pd.to_datetime(df['Time'])df['Time'] = pd.to_datetime(df['Time'], format='%d%b%Y:%H:%M:%S.%f')
  • 此代码用于将时间转换为 (datetime64[ns]) df['Time'] = pd.to_datetime(df['Time'], format='%H:%M:%S'),但 for 循环确实给出了错误 '&gt;=' not supported between instances of 'Timestamp' and 'datetime.time'

标签: python pandas for-loop jupyter


【解决方案1】:

你可以简化:

(21:00) & (07:30) the second are (03:00) & (10:00) 

到:

(21:00) & (10:00) 

所以解决方案是使用Series.betweennumpy.where

df=pd.DataFrame({'Time':['0:01:00','8:01:00','2021-08-13 10:19:10','12:01:00',
                        '14:01:00','18:01:01','23:01:00']})

df['Time'] = pd.to_datetime(df['Time']).dt.time


m = (df['Time'].between(dt.time(21,0,0), dt.time(23,23,23)) | 
      df['Time'].between(dt.time(0,0,0), dt.time(10,0,0)) | 
      df['Time'].between(dt.time(10,30,0), dt.time(14, 0,0)))

df['In/Out'] = np.where(m, 'In','Out')
print (df)
       Time In/Out
0  00:01:00     In
1  08:01:00     In
2  10:19:10    Out
3  12:01:00     In
4  14:01:00    Out
5  18:01:01    Out
6  23:01:00     In

【讨论】:

  • 时间没有按预期工作。有什么问题,我无法找出它是什么。代码中的 onse 之间的时间保存为 In,它应该说是 Out
  • @SoulSA - 你能说得更具体些吗?什么时候失败了?
  • 上午 10 点到 10:30 的时间应该保存在数据集中为out,而不是保存为in ...这是一个数据条目``` 2021-08-13 10 :19:10 在```
  • @SoulSA - 为我测试了运行良好的ans,添加了更改的数据来回答。
  • 工作就像一个魅力,感谢您的帮助兄弟。上帝保佑。
猜你喜欢
  • 2019-04-27
  • 2020-08-27
  • 1970-01-01
  • 2022-08-18
  • 2020-09-08
  • 2017-10-22
  • 2021-02-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多