pandas 系列/数据帧的条件递减

Conditional decrementation on a pandas series / dataframe

如何像这样更改 series/dataframe 中的值:

labels = df_known["labels"] # get dataframe

for label in labels:
    for c in classes_to_remove:
        if label > c:
            label -= 1 # doesn't actually change the label in the series, just the local variable

这会将每个标签递减 类 个比标签小的标签。

例如,如果 classes_to_remove = [1, 3]labels = [0, 2, 4] 我会递减 4 两次,因为它比 31 都大,递减 2 只一次,因为它只比 1 大并且保持 0 不变。最后labels = [0, 1, 2]

编辑:

示例: classes_to_remove = [2]

数据框:

labels
0        0
1        0
2        0
3        0
4        0
        ..
20596    6
20597    6
20598    6
20599    6
20600    6
Name: labels, Length: 15497, dtype: int64

np.unique(labels)
array([0, 1, 3, 4, 5, 6, 7], dtype=int64) # notice 2 is missing

预期数据帧:

np.unique(labels)
array([0, 1, 2, 3, 4, 5, 6], dtype=int64) 

我们可以使用 np.greater.outerlabelsclasses_to_remove 进行比较,然后 sum 沿 axis=1 生成的布尔掩码并从 labels 列得到结果

labels -= np.greater.outer([*labels], classes_to_remove).sum(1)

详情:

  1. 此处np.greater.outer用于比较每个标签与classes_to_remove
  2. 中的每个数字
>>> np.greater.outer([*labels], classes_to_remove)

array([[False, False],
       [ True, False],
       [ True,  True]])
  1. 现在,我们将上一步得到的布尔掩码沿轴求和=1
>>> np.greater.outer([*labels], classes_to_remove).sum(1)

array([0, 1, 2])
  1. 从标签中减去计算的总和得到结果
>>> labels - np.greater.outer([*labels], classes_to_remove).sum(1)

0    0
1    1
2    2
Name: labels, dtype: int64