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

时间:2017-08-14 19:55:25

标签: python pandas beautifulsoup

我目前有一个带有BeautifulSoup列的Pandas DataFrame(它包含一个img对象)。我想为多个HTML标记添加一列(例如df['text_img_count'] = [len(x.find_all('img')) for x in df['beautiful_soup']] 标记的数量)。

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

apply

但使用apply应该更快,所以我想转换此代码。

我正在考虑编写一个小函数,我可以将其传递给def get_imgs_count(): ,类似于:

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

然后我会这样称呼它:

def get_tag_count(df, tag)

因为我要为一堆HTML标签做这个,所以我真的不想写出大量超级类似的功能。宁愿写下这样的东西:

get_tag_count(df, 'img')

然后像这样称呼它:

apply

但我认为我不能将带有参数的函数传递给apply ...

我如何才能从列表理解转换为使用sqoop import --connect jdbc:mysql://nn01.itversity.com/retail_export --username retail_dba --password itversity \ --table roles --split-by id_emp --check-column id_emp --last-value 5 --incremental append \ --target-dir /user/ingenieroandresangel/hive/roles --hive-import --hive-database poc --hive-table roles

谢谢!

1 个答案:

答案 0 :(得分:1)

我会使用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)