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
两次,因为它比 3
和 1
都大,递减 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.outer
将 labels
与 classes_to_remove
进行比较,然后 sum
沿 axis=1
生成的布尔掩码并从 labels
列得到结果
labels -= np.greater.outer([*labels], classes_to_remove).sum(1)
详情:
- 此处
np.greater.outer
用于比较每个标签与classes_to_remove
中的每个数字
>>> np.greater.outer([*labels], classes_to_remove)
array([[False, False],
[ True, False],
[ True, True]])
- 现在,我们将上一步得到的布尔掩码沿轴求和=1
>>> np.greater.outer([*labels], classes_to_remove).sum(1)
array([0, 1, 2])
- 从标签中减去计算的总和得到结果
>>> labels - np.greater.outer([*labels], classes_to_remove).sum(1)
0 0
1 1
2 2
Name: labels, dtype: int64
如何像这样更改 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
两次,因为它比 3
和 1
都大,递减 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.outer
将 labels
与 classes_to_remove
进行比较,然后 sum
沿 axis=1
生成的布尔掩码并从 labels
列得到结果
labels -= np.greater.outer([*labels], classes_to_remove).sum(1)
详情:
- 此处
np.greater.outer
用于比较每个标签与classes_to_remove
中的每个数字
>>> np.greater.outer([*labels], classes_to_remove)
array([[False, False],
[ True, False],
[ True, True]])
- 现在,我们将上一步得到的布尔掩码沿轴求和=1
>>> np.greater.outer([*labels], classes_to_remove).sum(1)
array([0, 1, 2])
- 从标签中减去计算的总和得到结果
>>> labels - np.greater.outer([*labels], classes_to_remove).sum(1)
0 0
1 1
2 2
Name: labels, dtype: int64