我有一个列表和一个数据框,其中有一个名为Description的列,看起来像这样:
my_list = ['dog','cat','bird'...]
df
| Description |
|three_legged_dog0named1_Charlie|
| catis_mean |
| 1hippo_stepped-on_an_ant |
我想编写一个for循环,循环遍历df中的每一行,并检查它是否包含列表中的元素,如果包含,则打印该元素。
通常我会使用search(),但我不知道它如何与列表一起使用。我可以编写一个for循环来捕获所有情况,但是我不想这样做。还有另一种方法吗?
for i in df['Description']:
if i is in my_list:
print('the element that is in i')
else:
print('not in list')
输出应为:
dog
cat
not in list
如果想使用非大熊猫循环法测试用于Series.str.findall
与Series.str.join
供参加了所有mateched值,
和最后一个Series.replace
空字符串:
my_list = ['dog','cat','bird']
df['new'] = (df['Description'].str.findall('|'.join(my_list))
.str.join(',')
.replace('','not in list'))
print (df)
Description new
0 three_legged_dog0named1_Charlie dog
1 catis_mean cat
2 1hippo_stepped-on_an_ant not in list
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句