【问题标题】:How to get weekday of datetime.date object如何获取 datetime.date 对象的工作日
【发布时间】:2020-07-10 08:38:30
【问题描述】:

在如下的df中:

        id      timestamp               temperature 
27581   27822   2020-01-02 07:53:05.173 19.5    
27582   27823   2020-01-02 07:53:05.273 20.0    
27647   27888   2020-01-02 10:01:46.380 20.5    
27648   27889   2020-01-02 10:01:46.480 21.0    
27649   27890   2020-01-02 10:01:48.463 21.5    
27650   27891   2020-01-02 10:01:48.563 22.0    
27711   27952   2020-01-02 10:32:19.897 21.5    
27712   27953   2020-01-02 10:32:19.997 21.0
27861   28102   2020-01-02 11:34:41.940 21.5    
...

在生成情节的 for 循环中,我想在情节标题内打印 date 的工作日。 date 是一个 datetime.date 对象。但是我在格式化日期时遇到了一些错误。我根据this answer:

尝试了类似的方法
df['Date'] = df['timestamp'].dt.date     
df.set_index(df['timestamp'], inplace=True)


for date in df['Date'].unique():   
  df_date = df[df['Date'] == date]

  ...

  plt.title(date, date.strftime('%B'))    # I want to print both the date and the corresponding weekday.

日期以2020-01-01 格式显示日期,这很好,但工作日部分返回错误:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-56-6cc9c07f6879> in <module>()

---> 86   plt.title(date, date.strftime('%B'))
     87 
     88   number.append(np.count_nonzero(df2['events'][minLim:maxLim]))

2 frames
/usr/local/lib/python3.6/dist-packages/matplotlib/text.py in update(self, kwargs)
    174         # Update bbox last, as it depends on font properties.
    175         sentinel = object()  # bbox can be None, so use another sentinel.
--> 176         bbox = kwargs.pop("bbox", sentinel)
    177         super().update(kwargs)
    178         if bbox is not sentinel:

AttributeError: 'str' object has no attribute 'pop'

然后我尝试了这个,基于this answer

df['Date'] = df['timestamp'].dt.date     
df.set_index(df['timestamp'], inplace=True)


for date in df['Date'].unique():   
  df_date = df[df['Date'] == date]

  ...

  year, month, day = (int(x) for x in date.split('-'))    
  answer = datetime.date(year, month, day).weekday()
  plt.title(date, answer)

返回的

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-57-03b7529a410a> in <module>()
     82   number = []
     83   ax.autoscale() 
---> 84   year, month, day = (int(x) for x in date.split('-'))
     85   answer = datetime.date(year, month, day).weekday()
     86   plt.title(date, answer)

AttributeError: 'datetime.date' object has no attribute 'split'

更新:

我尝试使用以下方法在日期框架中为每个唯一的“日期”创建“工作日”列:

for date in df['Date'].unique():   
  df_date = df[df['Date'] == date]

  df_date['Date'] = pd.to_datetime(df_date['Date'], errors='coerce')
  df_date['Weekday'] = df_date['Date'].dt.dayofweek  #Add 'Weekday' column.

  print(df_date)

返回警告:

/usr/local/lib/python3.6/dist-packages/ipykernel_launcher.py:7: SettingWithCopyWarning:

A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead

See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy

尽管已打印警告数据框df_date。但是我应该如何让它从循环中返回both dateweekday(例如"2020-04-02, Thursday")?

我应该使用这样的东西吗:

weekday = df_date.loc[date, df_date['Weekday']]

要在循环中获取date 对应的工作日?

【问题讨论】:

    标签: python pandas numpy datetime for-loop


    【解决方案1】:

    使用 DatetimeIndex 的 weekday 属性 link。请参阅链接页面底部的示例。

    例子

    import pandas as pd
    import matplotlib.pyplot as plt
    
    data = [
        ["2020-01-02 10:01:48.563", "22.0"],
        ["2020-01-02 10:32:19.897", "21.5"],
        ["2020-01-02 10:32:19.997", "21.0"],
        ["2020-01-02 11:34:41.940", "21.5"],
    ]
    
    df = pd.DataFrame(data)
    df.columns = ["date", "temp"]
    
    df["date"] = pd.to_datetime(df["date"])
    df["weekday"] = df["date"].dt.weekday
    df["day_name"] = df["date"].dt.day_name()
    
    print(df)
    
    for day_name in df["day_name"].unique():
        plt.figure()
        plt.plot(df["date"], df["temp"])
        plt.title(day_name)
    plt.show()
    

    给了

                         date  temp  weekday  day_name
    0 2020-01-02 10:01:48.563  22.0        3  Thursday
    1 2020-01-02 10:32:19.897  21.5        3  Thursday
    2 2020-01-02 10:32:19.997  21.0        3  Thursday
    3 2020-01-02 11:34:41.940  21.5        3  Thursday
    

    和剧情


    更新 04/04 以回应评论

    import pandas as pd
    import matplotlib.pyplot as plt
    
    data = [
    ["2020-01-02 10:01:48.563", "22.0"],
    ["2020-01-02 10:32:19.897", "21.5"],
    ["2020-01-02 10:32:19.997", "21.0"],
    ["2020-01-02 11:34:41.940", "21.5"],
    ]
    
    df = pd.DataFrame(data)
    df.columns = ["timestamp", "temp"]
    df["timestamp"] = pd.to_datetime(df["timestamp"])
    
    df['Date'] = df['timestamp'].dt.date
    df.set_index(df['timestamp'], inplace=True)
    
    df['Weekday'] = df.index.day_name() 
    
    for date in df['Date'].unique():
      df_date = df[df['Date'] == date]
    
      plt.figure()
      plt.plot(df_date["timestamp"], df["temp"])
      plt.title("{}, {}".format(date, df_date["Weekday"].iloc[0]))
      plt.show()
    

    请注意,这将为每个唯一日期生成一个图,我假设这就是您所追求的。

    对于上面的有限数据示例,这会产生图

    【讨论】:

    • 嗨嗨,在文档中它指出“此方法在具有日期时间值(使用 dt 访问器)或 DatetimeIndex 的两个系列上都可用。”但是plt.title(date, date.dayofweek()) 返回了AttributeError:'datetime.date' object has no attribute 'dayofweek'
    • @nilsinelabore 添加了一个使用(部分)您的数据的示例。希望能说明如何使用它。
    • 嗨嗨,感谢您对答案的编辑。我试过你的代码。我认为它作为数据框的一部分在该系列中运行良好,但我仍在努力将其插入 Matplotlib 标题。我用df["weekday"] = df["Date"].dt.weekday 创建了一个新列,并将标题部分更改为plt.title(date, df['weekday']),它返回TypeError: pop() takes 2 positional arguments but 3 were given。我想我不应该对标题这样做?知道什么应该是标题参数吗?如果您认为有必要,我可以上传完整的代码。非常感谢...
    • @nilsinelabore 因为你将许多参数传递给 plt.title,它只需要一个字符串值(即标题),所以你必须在标题中获得你想要的特定工作日。我添加了一个我认为你所追求的情节示例。
    • 嗨嗨,谢谢您的回复。实际上,我想在标题中同时包含日期和工作日,例如“2020-04-02,星期四”。你知道我可以如何调整我的代码来做到这一点吗?
    猜你喜欢
    • 2021-11-20
    • 2013-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多