首页 > 解决方案 > 使用列表中的值填充熊猫列

问题描述

这是我的清单:

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 在列表中。

标签: pythonpandas

解决方案


你可以做:

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.

要返回Trueor False,只需删除返回的部分。

df['hit'] = df['dt_object'].isin(my_list)

推荐阅读