python - 将常量列添加到 Pandas 数据框的更好方法

标签 python pandas

目前,当我必须向现有数据框添加常量列时,我会执行以下操作。对我来说,它似乎并不那么优雅(我乘以数据帧长度的部分)。想知道是否有更好的方法来做到这一点。

import pandas as pd

testdf = pd.DataFrame({'categories': ['bats', 'balls', 'paddles'],
                       'skus': [50, 5000, 32],
                       'sales': [500, 700, 90]})

testdf['avg_sales_per_sku'] = [testdf.sales.sum() / testdf.skus.sum()] * len(testdf)

最佳答案

您可以通过仅提供一个数字来隐式填充该列。

testdf['avg_sales_per_sku'] = testdf.sales.sum() / testdf.skus.sum() 

来自 the documentation :

When inserting a scalar value, it will naturally be propagated to fill the column

关于python - 将常量列添加到 Pandas 数据框的更好方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29337058/

相关文章:

python-3.x - Pandas 使用除 apply 之外的许多条件添加新列的替代方法

python - 如何将不规则时间序列重新采样为每日频率并将其跨越到今天?

python - matplotlib 的 'webagg' 后端可以与我的 Django 站点一起使用吗?

python - 在 twilio Rest API 上使用 Status_Callback

python - 将列添加到 pandas 数据框中,其中包含每行的最大值以及相应的列名称

python - 为什么我的 Python 函数不将列转换为日期时间格式

python - 使用 for 循环遍历日期

python - Openshift:OSError Errno 98 无法更新服务器

python - 如何在 Python 中修正超平面的位置?

python - 使用正则表达式从 html 中提取电子邮件