python - Pandas:将函数应用于行,写入新列
问题描述
将函数应用于数据框
我目前有以下数据框:
数据
url visitors
http://somedomain.com 200000
http://someotherdomain.com 150000
http://somenewdomain.com 11000
对于数据框中的每一行,我喜欢将两个函数应用于 url 列,然后将每个结果写入两个不同的列“元”和“内容”。
职能:
def metacrawler(url)
...
return data
def contentcrawler(url)
...
return data
# Counter
progress = 0
环形
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
但是,当我在几次迭代后中止该过程时,我发现没有数据写入数据框中。也没有创建任何列。
我做错什么了?
解决方案
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')
解决方案
您可以将.apply()
功能Docs与result_type='expand'
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
编辑:如果要显示进度,请单独定义应用功能,即
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
推荐阅读
- android - 使用生物识别 androidX 库 1.1.0 崩溃
- python - Python:将多列与一列进行比较,并将大于该列的值替换为 NaN
- cucumber - 特征文件包含(和/。如何转义?
- css - Froala tableCellStyles 边框未更新
- victory-charts - 在胜利图上根据 y 轴绘制彩色背景
- unity3d - 我有一个 Unity 图像格式问题
- php - 如何从 VS Code 侧边栏中隐藏二进制文件?
- php - PHP 中带有自动欢迎电子邮件的注册表单
- kotlin - 如何在 Kotlin 中获取泛型类的内部类型?
- firebase - “NoSuchMethodError:在 null 上调用了 getter 'docs'”错误 Flutter Firebase