python - 使用列表中的值填充熊猫列
问题描述
这是我的清单:
my_list = [
2002-01-11 22:15:00,
2002-02-12 10:30:00,
2002-03-14 02:30:00,
2002-04-12 22:15:00
]
我有数据框:
dt_object diff
0 2002-01-01 00:00:00 -160.95041
1 2002-01-01 00:15:00 -160.81016
2 2002-01-01 00:30:00 -160.66989
3 2002-01-01 00:45:00 -160.52961
4 2002-01-01 01:00:00 -160.38930
我想在列表中的日期匹配时默认创建具有 False 值和 True 值的新列 'Hit'。
预期输出:
dt_object diff hit
0 2002-01-01 00:00:00 -160.95041 False
1 2002-01-01 00:15:00 -160.81016 False
2 2002-01-01 00:30:00 -160.66989 False
3 2002-01-01 00:45:00 -160.52961 False
4 2002-01-01 01:00:00 -160.38930 False
....................
....................
1010 2002-01-11 22:15:00 -150.54678 True
因为 2002-01-11 22:15:00 在列表中。
解决方案
你可以做:
import numpy as np
df['hit'] = np.where(df['dt_object'].isin(my_list),1,0)) # will give 1 or 0 according if the condition is satisfied.
要返回True
or False
,只需删除返回的部分。
df['hit'] = df['dt_object'].isin(my_list)
推荐阅读
- ios - 使用 Swift 和 KissXML 创建 XML:示例?
- python - 为什么我不能在 C# 中使用 ProcessStartInfo() 将参数传递给 python 文件
- laravel - 我想使用 Boostrap 库来制作模态
- c# - 用户退出时将文件保存在本地应用程序文件夹中
- algorithm - 使用 Q 查询遍历图中的最后一个节点
- mysql - 订阅 MySQL 表,以便在截断、删除或更改时提醒我
- python - 安装octave后找不到octave.exe,它在哪里?
- java - 如果可能,递归检查将一个数组拆分为两个满足特定条件的数组
- java - 从较新的活动返回时如何触发旧活动上的功能?
- c# - Getter 和 Setter - “值”如何工作,尤其是在 if 语句中?