简体   繁体   English

带有'datetime.date'的pandas Dateframe中的TypeError

[英]TypeError in pandas Dateframe with 'datetime.date'

I'm new to pandas and I would like to create a DataFrame for each weekday based on a bigger DataFrame with all kind of dates.我是熊猫的新手,我想为每个工作日创建一个基于具有各种日期的更大 DataFrame 的 DataFrame。

I read my initial data from a csv with the method data = pd.read_csv() and then my "Timestamp" column is set to datetime this way : data["Timestamp"] = pd.to_datetime(data["Timestamp"]) .我使用方法data = pd.read_csv()从 csv 读取我的初始数据,然后我的“时间戳”列以这种方式设置为日期data["Timestamp"] = pd.to_datetime(data["Timestamp"])data["Timestamp"] = pd.to_datetime(data["Timestamp"]) .

code :代码 :

import pandas as pd
from datetime import datetime
import calendar

data = pd.read_csv("stat.csv")
data["Timestamp"] = pd.to_datetime(data["Timestamp"])

dataMonday = data.loc[calendar.day_name[datetime.weekday(data["Timestamp"])] == "Monday"]

Now, here is the output :现在,这是输出:

TypeError: descriptor 'weekday' for 'datetime.date' objects doesn't apply to a 'Series' object

The only way I've found so far is to iterate with a for loop in the Timestamp column, but it appears to be a bad solution since I can hardly create another Dataframe based on that.到目前为止,我发现的唯一方法是在 Timestamp 列中使用for循环进行迭代,但这似乎是一个糟糕的解决方案,因为我几乎无法基于它创建另一个 Dataframe。

As the error suggests, you're trying to apply the weekday function to the whole series.正如错误所暗示的那样,您正在尝试将weekday函数应用于整个系列。 Instead, you need to apply the weekday method element-wise over the series.相反,您需要在系列按元素应用weekday方法。 apply is the tool for this: apply是用于此的工具:

dataMonday = data[data["Timestamp"].apply(datetime.weekday) == "Monday"]

Here is a way to add a column with the name of the weekday.这是一种添加带有工作日名称的列的方法。 This approach uses the .dt date accessor, and operates on the series, which is fast.这种方法使用.dt日期访问器,并在系列上运行,速度很快。

import pandas as pd
n = 8
t = pd.DataFrame({'x': [*range(n)], 
                  'Timestamp': pd.date_range(start='2020-01-01', periods=n, freq='D')})
t['Timestamp'] = pd.to_datetime(t['Timestamp']) # not needed in this example
t['weekday'] = t['Timestamp'].dt.day_name()
print(t)

   x  Timestamp    weekday
0  0 2020-01-01  Wednesday
1  1 2020-01-02   Thursday
2  2 2020-01-03     Friday
3  3 2020-01-04   Saturday
4  4 2020-01-05     Sunday
5  5 2020-01-06     Monday
6  6 2020-01-07    Tuesday
7  7 2020-01-08  Wednesday

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM