根据范围将日期时间分类为新列
I have a dataset called df
that looks like this:
provider | fid | pid | datetime |
---|---|---|---|
CHE-223 | 2bfc9a62 | 2f43d557 | 2021-09-26T23:18:00 |
CHE-223 | fff669e9 | 295b82e2 | 2021-08-13T09:10:00 |
我想创建一个名为wave
的新表,该表具有从dateTime
的日期范围的分类值。例如,从2019年11月16日到2020年2月28日的日期,它在Covid之前就具有价值。
我使用了循环函数来实现此目的,这是我使用的代码:
def wave(row):
if (row["datetime"] <= pd.Timestamp("2019-11-16")) & (row["datetime"] >= pd.Timestamp("2020-02-28")):
wave="before covid"
elif (row["datetime"] <= pd.Timestamp("2020-03-01")) & (row["datetime"] >= pd.Timestamp("2020-06-15")):
wave="1st wave"
elif (row["datetime"] <= pd.Timestamp("2020-06-16")) & (row["datetime"] >= pd.Timestamp("2020-09-30")):
wave="between waves"
elif (row["datetime"] <= pd.Timestamp("2020-10-01")) & (row["datetime"] >= pd.Timestamp("2021-01-15")):
wave="2nd wave"
df["wave"]=df.apply(lambda row:wave(row),axis=1)
但是它给了我列命名wave> wave
,但没有值。如何解决此问题并分类日期?
I have a dataset called df
that looks like this:
provider | fid | pid | datetime |
---|---|---|---|
CHE-223 | 2bfc9a62 | 2f43d557 | 2021-09-26T23:18:00 |
CHE-223 | fff669e9 | 295b82e2 | 2021-08-13T09:10:00 |
I wanted to create a new table called wave
that has categorical values for a range of date from datetime
. e.g. For the date from 16th of November 2019 until 28th of February 2020, it gives a value before covid and so on.
I used a loop function to achieve this and this is the code I used:
def wave(row):
if (row["datetime"] <= pd.Timestamp("2019-11-16")) & (row["datetime"] >= pd.Timestamp("2020-02-28")):
wave="before covid"
elif (row["datetime"] <= pd.Timestamp("2020-03-01")) & (row["datetime"] >= pd.Timestamp("2020-06-15")):
wave="1st wave"
elif (row["datetime"] <= pd.Timestamp("2020-06-16")) & (row["datetime"] >= pd.Timestamp("2020-09-30")):
wave="between waves"
elif (row["datetime"] <= pd.Timestamp("2020-10-01")) & (row["datetime"] >= pd.Timestamp("2021-01-15")):
wave="2nd wave"
df["wave"]=df.apply(lambda row:wave(row),axis=1)
But it gives me a column named wave
but with no values. How do I fix this and categorise the date?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的功能需要返回某些东西。此外,您的日期比较也被倒置:
在2019年11月16日之前和 2020年2月28日之后的匹配日期发生。
您的功能应该看起来像:
编辑:
&amp;
是一个角度操作员。对于逻辑表达式,请使用和
。Your function needs to return something. Also your dates comparisons are inverted:
would match dates that are before the 16th of November 2019 and at the same time after the 28th of February 2020... which of course never happens.
Your function should look like:
Edit: also
&
is a bit-wise operator. For logical expressions useand
.