Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/elixir/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 熊猫:将列表理解转换为使用Apply_Python_Pandas_Beautifulsoup - Fatal编程技术网

Python 熊猫:将列表理解转换为使用Apply

Python 熊猫:将列表理解转换为使用Apply,python,pandas,beautifulsoup,Python,Pandas,Beautifulsoup,我目前有一个带有beautiful\u soup列的熊猫数据框(它包含一个BeautifulSoup对象)。我想为几个HTML标记添加一列(例如img标记的数量) 例如,这是我使用列表理解的旧代码: df['text_img_count'] = [len(x.find_all('img')) for x in df['beautiful_soup']] 但是使用apply应该更快,所以我想转换这段代码 我正在考虑编写一个小函数,可以将其传递到apply,类似于: def get_imgs_co

我目前有一个带有
beautiful\u soup
列的熊猫数据框(它包含一个
BeautifulSoup
对象)。我想为几个HTML标记添加一列(例如
img
标记的数量)

例如,这是我使用列表理解的旧代码:

df['text_img_count'] = [len(x.find_all('img')) for x in df['beautiful_soup']]
但是使用
apply
应该更快,所以我想转换这段代码

我正在考虑编写一个小函数,可以将其传递到
apply
,类似于:

def get_imgs_count():
def get_tag_count(df, tag)
然后我会这样称呼它:

df['text_img_count'] = df['beautiful_soup'].apply(get_imgs_count)
get_tag_count(df, 'img')
因为我要为一堆HTML标签做这件事,所以我真的不想写太多超级相似的函数。我更喜欢这样写:

def get_imgs_count():
def get_tag_count(df, tag)
然后这样称呼它:

df['text_img_count'] = df['beautiful_soup'].apply(get_imgs_count)
get_tag_count(df, 'img')
但是我认为我不能将带有参数的函数传递给
apply

如何从列表理解转换为使用
apply


谢谢

我会使用
functools
'部分应用程序

from functools import partial
def get_tag_count(bs, tag):
    return [len(x.find_all(tag)) for x in bs]

get_image_count = partial(get_tag_count, tag = 'img')

df['text_img_count'] = df['beautiful_soup'].apply(get_image_count)

“但是使用apply应该更快,”你为什么这么想?事实上,我愿意承认,一个等价的列表理解将比
更快。apply
事实上,如果速度不是你想要的,你已经用
dtype=object
击中了自己的脚。在任何情况下,你都可以将参数传递给传递给
的函数。apply
,在
.apply
方法中使用关键字。不需要
部分
.apply
已经可以处理
函数的参数