按一天中的星期将DateTime分组

问题描述

我想,对于有经验的人来说,这应该是一个简单的问题。我想按星期几对记录进行分组,并希望在特定星期几有记录数。 这是我的DataFrame rent_week.info():

<class 'pandas.core.frame.DataFrame'>
Int64Index: 1689 entries,3 to 1832
Data columns (total 11 columns):
 #   Column        Non-Null Count  Dtype         
---  ------        --------------  -----         
 0   id            1689 non-null   int64         
 1   createdAt     1689 non-null   datetime64[ns]
 2   updatedAt     1689 non-null   datetime64[ns]
 3   endAt         1689 non-null   datetime64[ns]
 4   timeoutAt     1689 non-null   datetime64[ns]
 5   powerBankId   1689 non-null   int64         
 6   station_id    1689 non-null   int64         
 7   endplaceId    1686 non-null   float64       
 8   endStatus     1689 non-null   object        
 9   userId        1689 non-null   int64         
 10  station_name  1689 non-null   object        
dtypes: datetime64[ns](4),float64(1),int64(4),object(2)
memory usage: 158.3+ KB

“ createdAt”列中的数据看起来像“ 2020-07-19T18:00:27.190010000” 我正在尝试添加新列:

rent_week['a_day'] = rent_week['createdAt'].strftime('%A')

并收到错误返回:AttributeError:'Series'对象没有属性'strftime'。 同时,如果我写:

a_day = datetime.today()
print(a_day.strftime('%A'))

显示预期结果。据我了解,a_day和rent_week ['a_day']具有类似的类型datetime。 甚至通过以下方式请求:

rent_week['a_day'] = pd.to_datetime(rent_week['createdAt']).strftime('%A')

向我显示了相同的错误:没有strftime属性。 我什至没有开始对数据进行分组。我期望的结果是一个包含如下信息的DataFrame:

 a_day       number_of_records
Monday       101
Tuesday      55
...

解决方法

尝试a_day.dt.strftime('%A')-注意DataFrame列/系列对象上的其他.dt

背景:您做出的“相似”类型假设几乎是正确的。但是,由于列可能具有多种类型(数字,字符串,日期时间,地理等),因此,基础值的方法通常存储在名称空间中,以免使该系列本已广泛的API(方法计数)混乱自行输入。这就是为什么只能通过.str使用字符串函数,而只能通过.dt使用datetime函数的原因。

,

您可以创建一个lambda函数进行转换,然后将该函数应用于“ createdAt”列中的列。完成此步骤后,您可以根据需要进行分组。您可以从以下代码获取帮助:

rent_week['a_day'] = rent_week['createdAt'].apply(lambda x: x.strftime('%A'))

,

感谢Quamar和Ojdo的贡献。我发现了问题:它在索引中

<ipython-input-41-a42a82727cdd>:8: 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
  rent_week['a_day'] = rent_week['createdAt'].dt.strftime('%A')

我一旦重置索引

rent_week.reset_index()

两个变体都能正常工作!