【问题标题】:Assigning a numerical value to day and time为日期和时间分配数值
【发布时间】:2020-01-30 17:37:49
【问题描述】:

我在 df 中有一个列,其中包含与该行的客户每周时间相关的数值。例如,0 = 周日凌晨 12:0024 表示周一中午 12:005 表示周日凌晨 5:00

  Value 
    0
    4
    10
    24

  Value  Expected Output Column
    0           Sunday 12:00am
    4           Sunday 4:00am
    10          Sunday 10:00am
    24          Monday 12:00am
    49          Tuesday 1:00am

如果我希望将所有值分配给一周中正确的相应日期和时间,如何创建新列?值从 0 开始,代表星期天上午 12:00 的第一个值,到 167 结束,即该周的星期六晚上 11:59。

谢谢!

【问题讨论】:

    标签: python python-3.x pandas


    【解决方案1】:

    这就是你想要的:

    Value = pd.Series([0, 4, 10, 24, 49])
    AnyGivenSunday = pd.to_datetime('Sunday 2020') # yes this works
    (AnyGivenSunday + pd.to_timedelta(Value, 'h')).dt.strftime('%A %I:%M%P')
    

    【讨论】:

      【解决方案2】:
      import pandas as pd
      from datetime import datetime
      import calendar as cal
      
      df = pd.DataFrame(data={'val': [0, 0, 0, 0, 0], 'date': ["Sunday 12:00am", "Sunday 4:00am", "Sunday 10:00am", "Monday 12:00am", "Tuesday 1:00am"]})
      
      def convertDate(dateString):
          hour = datetime.strptime(dateString, '%A %I:%M%p').hour # Convert to 24 hour format
          day, time = dateString.split(" ") # Get text of day, cannot get datetime.weekday() without full date
          if day.lower() == cal.day_name[6].lower(): # cal.day_name index starts at Monday and not Sunday
              return hour + ((list(cal.day_name).index(day) - 6) * 24)
          else:
              return hour + ((list(cal.day_name).index(day) + 1) * 24)
      
      df['val'] = df['date'].apply(convertDate) # Apply function to all columns
      

      【讨论】:

        猜你喜欢
        • 2021-11-08
        • 2014-05-13
        • 1970-01-01
        • 1970-01-01
        • 2020-10-05
        • 1970-01-01
        • 1970-01-01
        • 2020-04-29
        • 2013-10-18
        相关资源
        最近更新 更多