从日期时间格式的给定时间修改给定值的标志
Modify flag for a given value from a given time for datetime format
让它成为下面的Python Panda DataFrame:
date
week_day
flag
2022-04-29 19:03:21
Friday
False
2022-05-23 21:30:04
Monday
False
2022-05-29 00:50:45
Sunday
True
2022-06-10 20:07:21
Friday
False
2022-06-17 17:23:22
Friday
False
2022-06-18 21:30:08
Saturday
True
我希望从 19:00:00 起每周五的标志为 True。也就是说得到下面的结果table.
date
week_day
flag
2022-04-29 19:03:21
Friday
True
2022-05-23 21:30:04
Monday
False
2022-05-29 00:50:45
Sunday
True
2022-06-10 20:07:21
Friday
True
2022-06-17 17:23:22
Friday
False
2022-06-18 21:30:08
Saturday
True
这是实现它的一种方法
筛选日期为星期五的行,然后使用日期时间,拆分小时并比较它是否为 19 或更大,并相应地将标志设置为 true,否则保持原样
np.where 允许有条件地更新标志
import datetime
import numpy as np
import pandas as pd
df['flag'] = np.where((df['week_day'] == 'Friday') & (df['date'].astype('datetime64').dt.strftime('%H') >= '19'),
True,
df['flag'])
或者,使用 dt.hour 而不是 strftime,正如 Quang Hoang 在评论中所建议的那样。
df['flag'] = np.where((df['week_day'] == 'Friday') & (df['date'].astype('datetime64').dt.hour >= 19),
True,
df['flag'])
df
date week_day flag
0 2022-04-29 19:03:21 Friday True
1 2022-05-23 21:30:04 Monday False
2 2022-05-29 00:50:45 Sunday True
3 2022-06-10 20:07:21 Friday True
4 2022-06-17 17:23:22 Friday False
5 2022-06-18 21:30:08 Saturday True
让它成为下面的Python Panda DataFrame:
date | week_day | flag |
---|---|---|
2022-04-29 19:03:21 | Friday | False |
2022-05-23 21:30:04 | Monday | False |
2022-05-29 00:50:45 | Sunday | True |
2022-06-10 20:07:21 | Friday | False |
2022-06-17 17:23:22 | Friday | False |
2022-06-18 21:30:08 | Saturday | True |
我希望从 19:00:00 起每周五的标志为 True。也就是说得到下面的结果table.
date | week_day | flag |
---|---|---|
2022-04-29 19:03:21 | Friday | True |
2022-05-23 21:30:04 | Monday | False |
2022-05-29 00:50:45 | Sunday | True |
2022-06-10 20:07:21 | Friday | True |
2022-06-17 17:23:22 | Friday | False |
2022-06-18 21:30:08 | Saturday | True |
这是实现它的一种方法
筛选日期为星期五的行,然后使用日期时间,拆分小时并比较它是否为 19 或更大,并相应地将标志设置为 true,否则保持原样
np.where 允许有条件地更新标志
import datetime
import numpy as np
import pandas as pd
df['flag'] = np.where((df['week_day'] == 'Friday') & (df['date'].astype('datetime64').dt.strftime('%H') >= '19'),
True,
df['flag'])
或者,使用 dt.hour 而不是 strftime,正如 Quang Hoang 在评论中所建议的那样。
df['flag'] = np.where((df['week_day'] == 'Friday') & (df['date'].astype('datetime64').dt.hour >= 19),
True,
df['flag'])
df
date week_day flag
0 2022-04-29 19:03:21 Friday True
1 2022-05-23 21:30:04 Monday False
2 2022-05-29 00:50:45 Sunday True
3 2022-06-10 20:07:21 Friday True
4 2022-06-17 17:23:22 Friday False
5 2022-06-18 21:30:08 Saturday True