假设输入是

d = {'col1': [1,2,3,4,5,6,7,8,9,10], 
 'col2': [1,2,3,4,5,6,7,8,9,10],
 'col3': [1,2,3,4,5,6,7,8,9,10],
 'offset': [1,2,3,1,2,3,1,2,3,1]} 

df = pd.DataFrame(data=d)

我想创建一个附加列,如下所示:

df['output'] = [1, 4, 9, 4, 10, 18, 7, 16, 27, 10]

基本上,offset中的每一个数字都告诉你要求和的列数(从col1作为参考点).

有没有一种矢量化的方法可以做到这一点,而不用遍历offset中的每个值?

推荐答案

你用np.select.要使用它,请创建sum列中的每个列(1、2、3…根据需要)作为可能的选项,并为偏移列中的每个值创建一个布尔掩码作为可能的条件.

# get all possible values from offset
lOffset = df['offset'].unique()

# get te result with np.select
df['output'] = np.select(
    # create mask for each values in offset
    condlist=[df['offset'].eq(i) for i in lOffset],
    # crerate the sum over the number of columns per offset value
    choicelist=[df.iloc[:,:i].sum(axis=1) for i in lOffset]
)
print(df)
#    col1  col2  col3  offset  output
# 0     1     1     1       1       1
# 1     2     2     2       2       4
# 2     3     3     3       3       9
# 3     4     4     4       1       4
# 4     5     5     5       2      10
# 5     6     6     6       3      18
# 6     7     7     7       1       7
# 7     8     8     8       2      16
# 8     9     9     9       3      27
# 9    10    10    10       1      10

注意:这假定偏移量列是最后一列

Python相关问答推荐

使用Curses for Python保存和恢复终端窗口内容

Docker-compose:为不同项目创建相同的容器

从 struct 类型创建MultiPolygon对象,并使用Polars列出[list[f64]列

具有2D功能的Python十六进制图

已删除的构造函数调用另一个构造函数

在Python中管理多个OpenGVBO和VAO实例

如何在Python中使用时区夏令时获取任何给定本地时间的纪元值?

三个给定的坐标可以是矩形的点吗

根据条件将新值添加到下面的行或下面新创建的行中

acme错误-Veritas错误:模块收件箱没有属性linear_util'

try 与gemini-pro进行多轮聊天时出错

我想一列Panadas的Rashrame,这是一个URL,我保存为CSV,可以直接点击

将输入聚合到统一词典中

移动条情节旁边的半小提琴情节在海运

* 动态地 * 修饰Python中的递归函数

如何使用两个关键函数来排序一个多索引框架?

如何排除prefecture_related中查询集为空的实例?

为什么我的sundaram筛这么低效

Odoo16:模板中使用的docs变量在哪里定义?

无法在Spyder上的Pandas中将本地CSV转换为数据帧