首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >熊猫:将函数应用于行,将其写入新列

熊猫:将函数应用于行,将其写入新列
EN

Stack Overflow用户
提问于 2018-10-17 09:42:21
回答 1查看 266关注 0票数 0

函数在数据挖掘中的应用

我目前有以下数据:

数据

代码语言:javascript
复制
url                            visitors
http://somedomain.com          200000
http://someotherdomain.com     150000
http://somenewdomain.com       11000

对于dataframe中的每一行,我喜欢将两个函数应用到url列,然后将每个结果写成两个不同的列“meta”和“content”。

函数:

代码语言:javascript
复制
def metacrawler(url)
    ...
    return data

def contentcrawler(url)
    ...
    return data

# Counter
progress = 0

代码语言:javascript
复制
for index, row in data.iterrows():
    print(str(progress)," out of ",str(len(data)))
    print('Starting meta crawling.')
    row['meta'] = metacrawler(row["url"])
    print('Starting content crawling.')
    row['content'] = contentcrawler(row["url"])
    print('Complete.')
    progress += 1

然而,当我在几次迭代后中止这个过程时,我发现没有数据被写入数据框架中。也没有创建列。

我做错什么了?

溶液

代码语言:javascript
复制
def func(row):
    print("Crawling Meta")
    meta = metacrawler(row["url"])
    print("Crawling Content")
    tags = contentcrawler(row["url"])
    return meta, content

data[['meta', 'content']] = data.apply(func, axis=1, result_type='expand')
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-10-17 10:13:43

可以将.apply()函数文档result_type='expand'一起使用。

代码语言:javascript
复制
In [3]: df = pd.DataFrame({'one':[1,2,3,4], 'two':[5,6,7,8]})

In [4]: df.apply(lambda x: (sum(x), sum(x)), axis=1, result_type='expand')
Out[4]:
    0   1
0   6   6
1   8   8
2  10  10
3  12  12

In [5]: df[['new', 'etc']] = df.apply(lambda x: (sum(x), sum(x)), axis=1, result_type='expand')

In [6]: df
Out[6]:
   one  two  new  etc
0    1    5    6    6
1    2    6    8    8
2    3    7   10   10
3    4    8   12   12

编辑:如果您想显示进度,请分别定义应用的函数,即

代码语言:javascript
复制
def func(row):
    print(row)
    return sum(row), sum(row)


In [3]: df = pd.DataFrame({'one':[1,2,3,4], 'two':[5,6,7,8]})

In [4]: df.apply(func), axis=1, result_type='expand')
Out[4]:
    0   1
0   6   6
1   8   8
2  10  10
3  12  12

In [5]: df[['new', 'etc']] = df.apply(lambda x: (sum(x), sum(x)), axis=1, result_type='expand')

In [6]: df
Out[6]:
   one  two  new  etc
0    1    5    6    6
1    2    6    8    8
2    3    7   10   10
3    4    8   12   12
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52851797

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档