[英]grouping DateTime by week of the day
我想,对于有经验的人来说,这应该是一个简单的问题。 我想按周对记录进行分组,并在特定的工作日拥有记录数。 这是我的数据帧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'] 具有类似的日期时间类型。 甚至通过以下方式请求:
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
。
您可以创建一个用于转换的 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()
两种变体都按预期工作!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.