创建一个 "Business Hour" 列以指示特定时间戳是否在 pandas 的工作时间内
create a "Business Hour" column to indicate whether a particular timestamp was within business hours in pandas
我正在尝试根据日期时间索引的值向数据框添加“Buiness_hour”。假设条目落在 0800 到 1800 之间,则“Business_hour”下的条目将 return“是”,否则“否”。
现有的df是这样的:
Index
UserID
2021-03-31 20:54:54
143173
2021-03-31 22:54:54
143173
2021-03-31 09:54:54
143173
我想插入“营业时间”栏,这样我就可以找出营业时间以外的交易数量
|索引 |用户名 | Business_hr |
|--------|--------|------------|
|2021-03-31 20:54:54|143173|否|
|2021-03-31 22:54:54|143173|否|
|2021-03-31 09:54:54|143173|是|
我尝试将 apply 与 lambda 函数一起使用
df['Business_hour'] = df.index.apply(lambda x: 'Yes' if df.index.hour >=9 and df.index.hour < 18 else 'No')
它说“'DatetimeIndex' 对象没有属性 'apply'”
然后我尝试了更基本的解决方案并得到了相同的结果:
def business_hr(x):
if x >=8 :
return 'Yes'
if x <=18:
return "Yes"
else:
'No'
df['Business_hr'] = df.index.hour.apply(business_hr)
我是 pandas 的新手,所以我试着了解它。花了几个小时研究,但到目前为止似乎运气不佳,所以希望有人能帮我一些忙。
首先感谢您的帮助和建议。
使用np.where
:
m = (9 <= df.index.hour) & (df.index.hour < 18)
df['Business_hour'] = np.where(m, 'Yes', 'No')
print(df)
# Output
UserID Business_hour
2021-03-31 20:54:54 143173 No
2021-03-31 22:54:54 143173 No
2021-03-31 09:54:54 143173 Yes
如果您想使用您的函数,请将 apply
(DataFrame) 替换为 map
(Series):
def business_hr(x):
return 'Yes' if 8 <= x < 18 else 'No'
df['Business_hour'] = df.index.hour.map(business_hr)
print(df)
# Output
UserID Business_hour
2021-03-31 20:54:54 143173 No
2021-03-31 22:54:54 143173 No
2021-03-31 09:54:54 143173 Yes
我正在尝试根据日期时间索引的值向数据框添加“Buiness_hour”。假设条目落在 0800 到 1800 之间,则“Business_hour”下的条目将 return“是”,否则“否”。
现有的df是这样的:
Index | UserID |
---|---|
2021-03-31 20:54:54 | 143173 |
2021-03-31 22:54:54 | 143173 |
2021-03-31 09:54:54 | 143173 |
我想插入“营业时间”栏,这样我就可以找出营业时间以外的交易数量 |索引 |用户名 | Business_hr | |--------|--------|------------| |2021-03-31 20:54:54|143173|否| |2021-03-31 22:54:54|143173|否| |2021-03-31 09:54:54|143173|是|
我尝试将 apply 与 lambda 函数一起使用
df['Business_hour'] = df.index.apply(lambda x: 'Yes' if df.index.hour >=9 and df.index.hour < 18 else 'No')
它说“'DatetimeIndex' 对象没有属性 'apply'”
然后我尝试了更基本的解决方案并得到了相同的结果:
def business_hr(x):
if x >=8 :
return 'Yes'
if x <=18:
return "Yes"
else:
'No'
df['Business_hr'] = df.index.hour.apply(business_hr)
我是 pandas 的新手,所以我试着了解它。花了几个小时研究,但到目前为止似乎运气不佳,所以希望有人能帮我一些忙。
首先感谢您的帮助和建议。
使用np.where
:
m = (9 <= df.index.hour) & (df.index.hour < 18)
df['Business_hour'] = np.where(m, 'Yes', 'No')
print(df)
# Output
UserID Business_hour
2021-03-31 20:54:54 143173 No
2021-03-31 22:54:54 143173 No
2021-03-31 09:54:54 143173 Yes
如果您想使用您的函数,请将 apply
(DataFrame) 替换为 map
(Series):
def business_hr(x):
return 'Yes' if 8 <= x < 18 else 'No'
df['Business_hour'] = df.index.hour.map(business_hr)
print(df)
# Output
UserID Business_hour
2021-03-31 20:54:54 143173 No
2021-03-31 22:54:54 143173 No
2021-03-31 09:54:54 143173 Yes