如何使用多索引筛选器为列赋值



当我使用多索引进行过滤时,我无法更新列上的值。

features_complete_new_index['ev_2'] = 1
features_complete_new_index.loc[true_positives_indexes,:].ev_2 = True
features_complete_new_index.loc[false_negatives_indexes,:].ev2 = False
features_complete_new_index.ev_2.value_counts()

输出

Out[20]:
1    8176700
Name: ev_2, dtype: int64

预期产出

1 7000000
True 1000000
False 17670000

我怀疑熊猫给你一个设置与复制警告警告。有一篇非常好的文章解释了进行"链式分配"的风险。

核心问题是当你写:

features_complete_new_index.loc[true_positives_indexes,:]

你不知道熊猫是在处理原始数据还是它的副本

所以在写作时:

features_complete_new_index.loc[true_positives_indexes,:].ev_2 = True

您可能要将 True 分配给数据帧的副本。

解决方案是在单个loc操作中执行此操作:

features_complete_new_index.loc[true_positives_indexes,'ev_2'] = True

文章中对此进行了很好的解释。

最新更新